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:
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;
}
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:
Idea #3:
Use a custom cell.
-[NSTextFieldCell editWithFrame:inView:editor:delegate:event:]
. There's also-[NSTextFieldCell setUpFieldEditorAttributes]
. I foundthis sample codeuseful.NSTextFieldCell
draw the text vertically centered.