Resizing cell font in NSTableView changes the cell in the next row

Viewed 35

I have a cell based table view that contains 5 columns, one of which is a name field. I'd like the point size of the text in the name field to change depending on the length of the text, so that the name is displayed fully (albeit smaller), rather than displayed with an ellipsis. My code works... sort of. Instead of changing the point size of the cell in current row (with the long name), the cell in the next row is changed. Another set of eyes to find the source of the problem would be greatly appreciated. Here's the code:

- (NSCell *)tableView:(NSTableView *)tableView dataCellForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)rowIndex {

    NSCell  *dataCell   = [tableColumn dataCell];
    int     pointSize;

    pointSize = 18;
    if ([dataCell isKindOfClass:[NSTextFieldCell class]]) {
        NSTextFieldCell *cell = [tableColumn dataCell];

        [cell setTextColor: [NSColor blackColor]];
        [cell setFont:[NSFont boldSystemFontOfSize:pointSize]];
            
        // This does not work as intended to shrink the size of the text (it actually shrinks the
        // cell in the NEXT row, not the current cell)
        NSDictionary    *attrs   = [NSDictionary dictionaryWithObject:[NSFont boldSystemFontOfSize:pointSize] forKey:NSFontAttributeName];
        NSSize          cellSize = [cell.stringValue sizeWithAttributes:attrs];

        while (cellSize.width >= tableColumn.width) {
            --pointSize;
            [dataCell setFont:[NSFont boldSystemFontOfSize:pointSize]];
            attrs    = [NSDictionary dictionaryWithObject:[NSFont boldSystemFontOfSize:pointSize] forKey:NSFontAttributeName];
            cellSize = [cell.stringValue sizeWithAttributes:attrs];
        }
    }
    return (dataCell);
}

So what I'm attempting to do is loop, comparing the attributed width of the text to the column width, reducing the font size each time through the loop until it fits. In testing the code I see that 'cell' is pointing to the correct text field by examine the stringValue, but when executed the text in the next row is actually the cell being altered.

This seems like a classic off-by-one problem, but my brain is not seeing the problem.

0 Answers
Related