2
votes

I've got an NSTableView which stretches from edge to edge on my window, but the data in the cells on the edge of the table really need some padding. The window doesn't look good if I leave a gutter on the edges, so I'd like to try to add some padding inside some of the cells so the data isn't right up against the edge.

I can't find anything in Interface Builder or in the code documentation about adding padding or insets to the cells.

Any suggestions?

3

3 Answers

5
votes

You can subclass NSTextFieldCell and override the drawInteriorWithFrame:inView: method to custom draw the string.

- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
    NSRect titleRect = [self titleRectForBounds:cellFrame];
    NSAttributedString *aTitle = [self attributedStringValue];
    if ([aTitle length] > 0) {
        [aTitle drawInRect:titleRect];
    }
}

where titleRectForBounds: adds some space

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

    titleRect.origin.x += 5;
    titleRect.origin.y += 5;

    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;
}

There's a more full example at http://comelearncocoawithme.blogspot.com/2011/09/custom-cells-in-nstableview-part-1.html

0
votes

Easy way: add spaces before your text strings. Better way: embed a view inside your cell and put all other UI objects inside that.

-1
votes

in your cellforrowAtIndexPath you need to implement this.

cell.textLabel.text = [NSString stringWithFormat:@" %@",sometext];

or else take a label and setframe to it.Then add it to cell