我有一个自定义表格 View 单元格,我想根据标签中的文本量自动调整其大小。
在我的 TableView Controller 中,我使用 UITableViewAutomaticDimension
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
if indexPath.row == 0 {
return 200
} else {
return 49
}
} else if indexPath.section == 1 {
return 100
} else if indexPath.section == 2 {
if indexPath.row == 0 {
return 200
} else {
return 400
}
} else {
return UITableViewAutomaticDimension
}
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
这就是我最终得到的结果。
最佳答案
您需要:
- 将标签的
top、trailing、leading、bottom
约束设置为IB中的superView - 设置
numberOfLines = 0
- 设置
内容抗压缩优先级垂直
和内容拥抱优先级垂直
- 在代码中设置
self.tableView.estimatedRowHeight = MinControlSize;
self.tableView.rowHeight = UITableViewAutomaticDimension;
设置文本后调用此
cell.setNeedsDisplay();
cell.layoutIfNeeded();
在委托(delegate)方法中
optional func tableView(_ tableView: UITableView,
heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
希望这有帮助。我从 Apple 的“ self 调整大小”示例中获取此内容
关于ios - 自动调整自定义 UITableViewCell 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37705094/