要设置行高和估计行高的自动尺寸,请确保执行以下步骤,自动尺寸对单元格/行高布局有效。
- 分配和实现dataSource和delegate
- 分配
UITableViewAutomaticDimension
给 rowHeight 和estimatedRowHeight
- 实现委托/数据源方法(即
heightForRowAt
并返回一个值UITableViewAutomaticDimension
给它)
-
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Don't forget to set dataSource and delegate for table
table.dataSource = self
table.delegate = self
// Set automatic dimensions for row height
// Swift 4.2 onwards
table.rowHeight = UITableView.automaticDimension
table.estimatedRowHeight = UITableView.automaticDimension
// Swift 4.1 and below
table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = UITableViewAutomaticDimension
}
// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Swift 4.2 onwards
return UITableView.automaticDimension
// Swift 4.1 and below
return UITableViewAutomaticDimension
}
对于 UITableviewCell 中的标签实例
- 设置行数 = 0(& 换行模式 = 截断尾部)
- 设置关于其超级视图/单元格容器的所有约束(顶部、底部、左右)。
- 可选:设置标签的最小高度,如果你想要标签覆盖的最小垂直区域,即使没有数据。
