UITableView:自动设置行的高度并用最大高度常量固定

UITableView: automatically set height for the row and fix it with max height constant

我需要自动设置行高。我用

theTable.estimatedRowHeight = 60
theTable.rowHeight = UITableViewAutomaticDimension

但是高度不固定。我需要固定高度,例如 MAX 60 高度,默认高度为 40。使用 estimatedRowHeight 时,高度不固定,当字符串很长时,单元格会占据所有屏幕。如何解决?

您需要将 table 视图单元格的所有内容放在一个视图中(我们称它为 MainView)并将 MainView 顶部、前缘和后缘约束设置为容器视图。还设置一个小于或等于 60 的高度限制,并具有所需的优先级。之后将您的标签放在 MainView 中,设置顶部、前导和尾随约束到 MainView,底部 space 到 MainView 约束,具有高优先级。同样在您的标签上将行数设置为 0,并将首选宽度设置为显式。这样,如果标签内容高度小于 60,MainView 将缩小并且仍然匹配小于或等于 60 的高度约束。否则,如果内容高度大于 60,MainView 的底部 space 约束将在没有导致问题,因为它的优先级低于 MainView 高度限制。

最终重写table查看委托方法如下

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
   return UITableViewAutomaticDimension
}

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 40
}