问题
There's been a lot of questions about how to make dynamic cell height using Autolayout and TextView inside it. Here's the story
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
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;
}
- 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