我有一个自定义UITableViewCell
。在UITableViewCell的contentView
中,我添加了一个UIButton
,下面的按钮有一个UILabel
(按钮和UILabel是彼此的兄弟姐妹)。
一开始,UILabel上不会有文本,因此其高度约束设置为>= 0。 但是当我点击按钮时,我设置了UILabel
的text属性,它应该变得可见。换句话说,我想扩展UILabel的高度,并且应该扩展UITableViewCell的高度。
我已将UIButton
Top,Leading
和Trailing
边缘固定到UITableViewCell
contentView
,同样,我将UILabel的Bottom,Leading
和Trailing
边缘固定到UITableViewCell
内容视图。
现在的问题是,当我点击UITableViewCell
时,它不会调整UILabel
大小,也不会调整UITableViewCell
。
这是我的代码
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
MYCustomCell *cell = (MYCustomCell *) [tableView cellForRowAtIndexPath:indexPath];
cell.descriptionLbl.text = @"This is my text";
[cell layoutSubviews];
}
同样地
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
MYCustomCell *cell = (MYCustomCell *) [tableView cellForRowAtIndexPath:indexPath];
cell.descriptionLbl.text = @"";
[cell layoutSubviews];
}
这是我的自定义单元格的布局子视图
- (void) layoutSubviews {
[super layoutSubviews];
self.descriptionLbl.preferredMaxLayoutWidth = CGRectGetWidth(self.contentView.bounds);
self.descriptionLbl.numberOfLines = 0;
[self.descriptionLbl sizeToFit];
if (self.descriptionLbl.text.length > 0){
self.descriptionLbl.frame = CGRectMake(self.descriptionLbl.frame.origin.x, self.descriptionLbl.frame.origin.y, self.descriptionLbl.frame.size.width, 50); // Here the size will be calculated more accurately later
}
}
请注意,我没有在任何地方设置UITableViewCell
的高度。
在您的情况下,您必须在只有按钮可见时手动管理自动布局约束,单击文本后将可见。我已经准备了一个演示,你可以在这里找到。
https://github.com/rushisangani/TableViewCellExpand
请参考 TableViewCell 的情节提要约束并明智地管理它。
最终你需要这样做 你的 -viewdidLoad
[_tableview setRowHeight:UITableViewAutomaticDimension];
[_tableview setEstimatedRowHeight:44];
UITableViewAutomaticDimension表示您的单元格高度是动态的,并设置估计的行高度,让您计算滚动高度
在表视图单元格中设置动态大小的视图时,正确设置所有约束非常重要。开发人员最常犯的错误是省略单元格上的底部垂直约束。
要获得有关如何在自定义UITableViewCells中设置动态调整大小的UILabels的更详细说明,请查看我在这里写的一篇文章。
Swift 2.0 :
添加这个:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension
}
或
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension
}
对于表视图控制器,请使用:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
self.tableView.setNeedsLayout()
self.tableView.layoutIfNeeded()
}