UITableViewAutomaticDimension 来适应子视图

UITableViewAutomaticDimension To fit subviews

我的应用有一个 table 视图,具有自动调整行高的大小(UITableViewAutomaticDimension 用于 heightForRow-Delegate-Function)。 我的自定义单元格有 子视图 ,它们可以有 不同的大小 (它们包含总是不同数量的条形图)。

但是,自动单元格高度无法适应 table 视图单元格子视图的这些不同大小。

只有 有效,如果我为 table 视图单元格中的子视图设置约束(例如 make.top.equalTo(self).offset(300) 和 snap kit) - 但是因为这些子视图可以有不同的大小,这不是一个干净的解决方案。

你知道更好的方法吗?

谢谢!

首先: 在 vi​​ewdidLoad 上(not 在委托中):

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140 //this estimation will improve performance (can be omitted), set the +/- size of most cases.

只是不要覆盖单元格高度委托。

第二个: 在您的单元格中,您添加了包含字符的子视图。添加该子视图约束,但更重要的是在该子视图和单元格(本例为超级视图)之间添加垂直间距。喜欢图片。

如果子视图高度将设置单元格高度。只需确保子视图中的字符即可设置子视图高度(有约束)。

For more details, here there's a good step by step.