Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTableView Row Height based on NSStrings

Basically, I have an NSTableView with 1 collumn, and I'm inserting long strings into each row. However, not all the strings are long, so I'd like the height of each row to be different based on how long the string is.

I've figured out that I need to ask the collumn how wide it is, and then ask the string how many lines it will take up if the collumn is that wide, and then decide how "tall" the NSCell will be. But how exactly do I go about doing that? I've gotten the collumn width from:

[[[tableView tableColumns] objectAtIndex:0] width];

but I can't figure out how to ask the NSString how much space it will take up. Or, perhaps, there is a better way that I should go about doing this?

Thanks for any help in advance.

like image 264
element119 Avatar asked Jul 09 '10 11:07

element119


2 Answers

Create an NSTextFieldCell instance and match its font/size/etc. to that of your column's data cell. Ask it for the -cellSizeForBounds:, passing in a rect of the desired width for the column, with a large height (FLT_MAX?). The result should be an NSSize whose height you can use.

It gets trickier if you have more than one multi-line text column because you'll need to consider all the cells in that row, taking the largest as your row height. If you expect a lot of rows on average, you'll probably want to cache this work, updating it as necessary, then simply referencing it when the row height delegate method is called.

like image 111
Joshua Nozzi Avatar answered Oct 16 '22 22:10

Joshua Nozzi


Code as per the above answer ...

    NSString *string = [[_tableViewDataSourceArray objectAtIndex:rowIndex] 
                              valueForKey:@"StringToDisplay"];

    NSTableColumn *tableColoumn = [aTableView
                              tableColumnWithIdentifier:@"TableColumnIdentifier"];

    if (tableColoumn) 
    {
     NSCell *dataCell = [tableColoumn dataCell];
     [dataCell setWraps:YES];
     [dataCell setStringValue:string];
     NSRect myRect = NSMakeRect(0, 0, [tableColoumn width], CGFLOAT_MAX);
     heightOfRow =  [dataCell cellSizeForBounds:myRect].height;
    }
like image 26
Robert D'Almeida Avatar answered Oct 16 '22 22:10

Robert D'Almeida