I need a little help with NSTableView and dynamic row height
What I have:
A single-column view-based NSTableVIew bound to an array controller. Each NSTableCellView contains three subviews: NSImageView, NSTextField (single line) and NSTextField (multiline). Basically, this is a chat interface, so you would have a list of messages, senders and avatars.
What I want to achieve:
When text is longer than minimum height of the row, the row expands to fit content. Much like iMessage, the bubbles expand to fit message.
...which seems like a very natural thing to do, but out of all the relevant solutions I found online, (Ref 1, Ref 2), none of which works for me.
Ref 2 looks fantastically written but none of that applies to my application since the example project uses third-party auto layout code and the entire thing is designed for iOS. Ref 1 gave a very promising solution written in, well, English. I tried to set it up using a "dummy view" like described in the solution, but failed to even properly change and measure the height.
Here's my code for tableView:heightOfRow:
, _samplingView
is the dummy view, which has working constraints and is identical to the one in tableView
.
- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
NSTextField *textField;
NSTextFieldCell *messageCell;
for (NSView *subview in [_samplingView subviews]) {
if ([[subview identifier] isEqualToString:@"message"]) {
textField = (NSTextField*)subview;
messageCell = ((NSTextField*)subview).cell;
}
}
Message *message = [[_messagesArrayController arrangedObjects] objectAtIndex:row];
_samplingView.objectValue = message;
CGFloat width = [[[tableView tableColumns] objectAtIndex:1] width];
[_samplingView setBounds:NSMakeRect(0, 0, width, CGFLOAT_MAX)];
[_samplingView display];
CGFloat optimalHeight = 10 + [messageCell cellSize].height; //messageCell's size stays the same when I change samplingView to try to measure the height
return optimalHeight;
}
Result: all row heights remain the same, somehow when I change the width of _samplingView
, it doesn't re-size messageCell
's size. I thought auto-layout would take care of this compression/expansion and allow me to measure the height. Indeed, I am very confused.
Edit: for reference, this is what my view looks like
+-----------+---------------------------------------------------+
| | NSTextField |
|NSImageView| sender |
| avatar +---------------------------------------------------+
| | |
| | NSTextField (multiline) |
+-----------| message |
| | |
| | (high compression/hugging priority) |
| | (this view should decide the height of row) |
| | |
+-----------+---------------------------------------------------+