根据调整大小标签调整 UITableViewCell 高度

Adjust UITableViewCell height according to the resizing label

我有一个习惯UITableViewCell。在 UITableViewCell 的 contentView 中,我添加了一个 UIButton,在按钮下方有一个 UILabel(按钮和 UILabel 是彼此的兄弟姐妹)。

一开始,UILabel 上没有文本,因此它的高度限制设置为 >= 0。但是当我点击按钮时,我设置了 UILabel 的文本 属性 , 它应该变得可见。换句话说,我想扩展 UILabel 的高度,也应该扩展 UITableViewCell 的高度。

我已将 UIButton Top,LeadingTrailing 边固定到 UITableViewCell contentView 并且类似地我已将 UILabel 的 Bottom,LeadingTrailing 边到 UITableViewCell contentsView.

现在的问题是,当我点击 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];
}

这是我的自定义单元格的 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 的高度。

最终你需要做你的 -viewdidLoad

[_tableview setRowHeight:UITableViewAutomaticDimension];
[_tableview setEstimatedRowHeight:44];

UITableViewAutomaticDimension 表示您的单元格高度是动态的,setEstimatedRowHeight 让您的滚动高度计算

在您的情况下,您必须在只有按钮可见且单击文本后可见时手动管理自动布局约束。 我已经为此准备了一个演示,您可以在此处找到。

https://github.com/rushisangani/TableViewCellExpand

请参考 TableViewCell 的故事板约束并明智地管理它。

在 table 视图单元格中设置动态大小的视图时,正确设置 所有 约束非常重要。开发人员最常犯的错误是忽略了单元格的底部垂直约束。

要更详细地了解如何在自定义 UITableViewCells 中设置动态调整大小的 UILabel,请查看 post 我写对了 here

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
}

如果是 Table 视图控制器,请使用:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
self.tableView.setNeedsLayout()
self.tableView.layoutIfNeeded()
}