How to change textview height constraint within table view cell?

感情迁移 提交于 2019-12-23 01:58:06

问题


There's been a lot of questions about how to make dynamic cell height using Autolayout and TextView inside it. Here's the story

  1. I follow this article iOS dynamic table view cells with varying row height and Autolayout. In this case, we replace the 2nd label in the article with a TextView, with the same set of constraints

  2. The TextView does not have intrinsic content size as the Label. So we must use sizeThatFits and creating height constraint on the TextView, like this.

This height constraint is an IBOutlet from the Nib

ViewController.m

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    Item *item = self.dataSource.items[indexPath.row];
    [self.prototypeCell configureWithModel:item];

    [self.prototypeCell updateConstraintsIfNeeded];
    [self.prototypeCell layoutIfNeeded];

    self.prototypeCell.textViewHeightConstraint.constant = [self.prototypeCell.textView sizeThatFits:CGSizeMake(self.prototypeCell.frame.size.width, CGFLOAT_MAX)].height;

    [self.prototypeCell updateConstraintsIfNeeded];
    [self.prototypeCell layoutIfNeeded];

    return [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
}

CustomCell.m

- (void)configureWithModel:(Item *)model {
    self.textView.text = model.content;
}
  1. I then see in the console that
Unable to simultaneously satisfy constraints.
  Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to

figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", "", "" )

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7fa3e3988a90 UITextView:0x7fa3e210f000.height == 200>

Here you can see that the Autolayout system removes the height constraint on the TextView.

The problem here is that we update the height constraint on the TextView, but the contentView of the cell seems to ignore this.

I know the key to this dynamic height is that the subviews (Label, TextView) must determine its own size (Label has its own intrinsic content size, for TextView we manually set its height constraint) so that the contentSize is then calculated

What am I missing?


回答1:


Simply lowering the priority of the textViewHeightConstraint (below 1000) fixes the Unable to simultaneously satisfy constraints problem



来源:https://stackoverflow.com/questions/30107872/how-to-change-textview-height-constraint-within-table-view-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!