NSTableCellView padding

1.3k views Asked by At

How can I add padding to a NSTableCellView?

I want the contents to have a padding of 10px, similar to how you would do it in plain HTML. (All sides). The text should be vertically centered in the middle.

At the moment I'm doing this in a subclass of NSTextFieldCell. But this doesn't seem to work correctly.

When I edit the text, the edit text field does not use the padding from the textfieldcell.

Image 2: Check image

Check image

Here is the code I currently have, (subclass of NSTextFieldCell)

- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
NSRect titleRect = [self titleRectForBounds:cellFrame];

NSAttributedString *aTitle = [self attributedStringValue];
if ([aTitle length] > 0) {
    [aTitle drawInRect:titleRect];
}
}

- (NSRect)titleRectForBounds:(NSRect)bounds
{
NSRect titleRect = bounds;

titleRect.origin.x += 10;
titleRect.origin.y = 2;

NSAttributedString *title = [self attributedStringValue];
if (title) {
    titleRect.size = [title size];
} else {
    titleRect.size = NSZeroSize;
}

// We don't want the width of the string going outside the cell's bounds
CGFloat maxX = NSMaxX(bounds);
CGFloat maxWidth = maxX - NSMinX(titleRect);
if (maxWidth < 0) {
    maxWidth = 0;
}

titleRect.size.width = MIN(NSWidth(titleRect), maxWidth);

return titleRect; 
}
2

There are 2 answers

2
tsnorri On BEST ANSWER

Below are some options for getting the padding.

Earlier I had some problems getting the correct bounding box height for NSAttributedString. I don't remember how I solved them but there are some discussions on the matter.

Idea #1:

Use NSTableView's intercell spacing. It's also available in the Interface Builder from the table view's size tab. Look for cell spacing.

Idea #2:

When editing the interface:

  • Unless you need something else, use the text or image and text table cell view provided by Apple.
  • Change the height of the table cell view inside the table view using the size tab.
  • Reposition the text field inside the table cell view.

Idea #3:

Use a custom cell.

  • You can change the field editor position by overriding -[NSTextFieldCell editWithFrame:inView:editor:delegate:event:]. There's also -[NSTextFieldCell setUpFieldEditorAttributes]. I found this sample code useful.
  • If you increase the height of the cell, there are a couple of ways to make NSTextFieldCell draw the text vertically centered.
2
Vincent Joy On

use the setContentInset method.it sets the distance of the inset between the content view and the enclosing table view.

for example

self.tableView.contentInset = UIEdgeInsetsMake(-35, 0, -20, 0);