NSTableCellView dynamic height with NSTextField multiline autolayout
Asked Answered
H

0

6

I have a view-based NSTableView and NSTableCellView subclass which having multiline NSTextField with word-wrap enabled. Now I want my table to have dynamic row height according to textfield content. Autolayout is also enabled.

Textfield's constraints is shown in image:

contstraints

Tableview heightForRow method code :

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {

    VerseTableCell *cell = [self getTableCellForRow:row];
    [cell.txtSuraDetail invalidateIntrinsicContentSize];
    [cell invalidateIntrinsicContentSize];
    [cell setTranslatesAutoresizingMaskIntoConstraints:YES];

    [cell layout];
    [cell setNeedsDisplay:YES];
    [cell setNeedsUpdateConstraints:YES];
    [cell setNeedsLayout:YES];
    [cell layoutSubtreeIfNeeded];

    NSRect size = cell.txtSuraDetail.frame;

    CGFloat height = (size.size.height) + 30;

    return height;
   }

Cell Layout Method :

- (void)layout {
    [super layout];
    self.txtSuraDetail.preferredMaxLayoutWidth = self.txtSuraDetail.frame.size.width;
}

I've tried the following links but nothing helped, textfield's text is still cutting.

Hillside answered 8/2, 2017 at 5:46 Comment(7)
This has gotten a lot easier recently. Check out .usesAutomaticRowHeights in macOS 10.13 as described here: developer.apple.com/library/content/releasenotes/AppKit/… (In the section titled NSTableView Automatic Row Heights).Denton
@CliftonLabrum I hope I'm wrong here but I don't believe AutomaticRowHeights works with multi-line wrapping text.Equestrian
I think it should work as long as you have the right auto layout constraints on the text field.Denton
@CliftonLabrum do you know what those would be? Without a height constraint on the textview, it simply defaults to 1. I have tried everything at this point.Equestrian
You have to set top and bottom constraints on the NSTextField and remove the height constraint. I believe you also have to set the number of lines in the field to 0.Denton
@Equestrian Did you get any solution for this issue? I have the same problem, struggling to fix.Fronton
@noundla Yes I did, its a little tricky. I may be misremembering some of it as I’m not in front of any code but in your tableview delegate you need to access the datasource directly. In the rowheight method you get the text youll need for the label, and then put that in to a textfield/tableviewrow that you created to serve as a sizing template, not associated with any views, etc. use it to get the height and return that, and let autolayout do the rest. Ill try to post a full code answer but there is a similar problem with dynamic sizing in collection views that i answered in my post history.Equestrian

© 2022 - 2024 — McMap. All rights reserved.