Question

I know that in a view-based table view, the row class NSTableCellView subclasses from NSView. This class contains two properties, an NSTextField and an NSImageView. I am only using the NSTextField without an image view. However, some cells in my table view must contain multiple lines of text, while others may only contain one or two lines. I need to be able to resize individual NSTableCellView views depending on the size of their NSTextField textField property.

Therefore, I needed to do the following:

  1. Get the frameSize of the NSTextField in the table cell view.
  2. Set the frameSize of the NSTableCellView to the frameSize of the NSTextField (the one we got in set one)

However, this approach hasn't been working. I have begun to think that my approach to resize the NSTableCellView is incorrect. Here is the code that I have been using:

[tableCellView setFrameSize:[[tableCellView textField] frame].size];
[tableCellView setNeedsDisplay:YES];

Is there a problem with this approach? I would expect the cell to resize, but it doesn't? What is going wrong?

Thanks.

Was it helpful?

Solution

[edit] I should have started by commenting that the size of the textField has little to do with how large it would need to be to display all of its content.

I use this code to determine the height of a string based on the width of a table cell:

- (CGFloat) displayStringHeightWithWidth:(CGFloat)width
{
    CGSize size = NSMakeSize(width,0);
    NSRect bounds = [self.displayString boundingRectWithSize:size 
        options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading];
    return bounds.size.height;
}

Ideally you can adapt that to finding the height of the textField.stringValue or textField.attributedStringValue. Not that the above is also from OSX, not iOS, so YMMV on some of the fluff.

So that changes your algorithm to:

  1. Get the width of the table column
  2. Get the height of the required bounding rect for the textfield's text
  3. Tell the tableView that the row height is whatever you found in 2

Now. Regarding #3. I believe that you have to use the tableView:heightOfRow: in NSTableViewDelegate protocol as well as call the table's noteHeightOfRowsWithIndexesChanged: to have row heights change. The tableView's not otherwise aware that the height of your cell has changed. Note the discussion in the documentation. It could be your method would work without the delegate and just telling the table that the row heights for the rows that you are changing are dirty... but I wouldn't really expect it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top