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.

pkamb
  • 33,281
  • 23
  • 160
  • 191
tanvi2009
  • 61
  • 3
  • 2
    This has gotten a lot easier recently. Check out `.usesAutomaticRowHeights` in **macOS 10.13** as described here: https://developer.apple.com/library/content/releasenotes/AppKit/RN-AppKit/#10_13 (In the section titled **NSTableView Automatic Row Heights**). – Clifton Labrum Nov 01 '17 at 23:21
  • @CliftonLabrum I hope I'm wrong here but I don't believe AutomaticRowHeights works with multi-line wrapping text. – NickSpag Apr 02 '18 at 20:53
  • I think it should work as long as you have the right auto layout constraints on the text field. – Clifton Labrum Apr 02 '18 at 21:00
  • @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. – NickSpag Apr 02 '18 at 23:50
  • 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`. – Clifton Labrum Apr 03 '18 at 19:52
  • @NickSpag Did you get any solution for this issue? I have the same problem, struggling to fix. – Noundla Sandeep Jun 05 '18 at 16:44
  • 1
    @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. – NickSpag Jun 13 '18 at 16:36

0 Answers0