自动调整单元格在 iOS 11 中不起作用
Autosizing Cells Not Working in iOS 11
我正在从 Web 服务填充我的 UITableView。这是所有的限制条件。某些商品(例如芝士汉堡)有 10 行未显示的文本。
结果如下:
要启用 UITableViewCell
的自动调整大小,请在控制器的 viewDidLoad()
方法中设置 UITableView
的 rowHeight
和 estimatedRowHeight
,如下所示:
self.tableView.estimatedRowHeight = 150.0
self.tableView.rowHeight = UITableViewAutomaticDimension
然后,如果您想要或需要实施 heightForRow
UITableViewDelegate
方法,请不要忘记再次将 UITableViewAutomaticDimension
传递给任何 row
或section
需要自动调整单元格大小,如下所示:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let section = indexPath.section
if let itemSection = ItemTableViewSections(rawValue: section) {
switch itemSection {
case .header: return 80.0
case .photos: return 95.0
case .note: return UITableViewAutomaticDimension
case .rejectOptions: return 50.0
}
}
return 0
}
最后,如果答案真的像您上一个问题一样回答了您的问题,请不要忘记select一个答案:)
编辑:我制作了一个示例项目,该项目使用 Storyboard 并仅针对 iOS11。一切正常。 只是不要忘记设置标签的约束条件 - 顶部、底部、前导和尾随。自动调整单元格需要这些约束。最后,将 UILabel
的行数设置为 0。
将 垂直内容拥抱优先级 增加 1 UILabel
当所有其他方法都失败时,请尝试将内容压缩阻力优先级设置为 1000。这就是我解决问题的方法。
我正在从 Web 服务填充我的 UITableView。这是所有的限制条件。某些商品(例如芝士汉堡)有 10 行未显示的文本。
结果如下:
要启用 UITableViewCell
的自动调整大小,请在控制器的 viewDidLoad()
方法中设置 UITableView
的 rowHeight
和 estimatedRowHeight
,如下所示:
self.tableView.estimatedRowHeight = 150.0
self.tableView.rowHeight = UITableViewAutomaticDimension
然后,如果您想要或需要实施 heightForRow
UITableViewDelegate
方法,请不要忘记再次将 UITableViewAutomaticDimension
传递给任何 row
或section
需要自动调整单元格大小,如下所示:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let section = indexPath.section
if let itemSection = ItemTableViewSections(rawValue: section) {
switch itemSection {
case .header: return 80.0
case .photos: return 95.0
case .note: return UITableViewAutomaticDimension
case .rejectOptions: return 50.0
}
}
return 0
}
最后,如果答案真的像您上一个问题一样回答了您的问题,请不要忘记select一个答案:)
编辑:我制作了一个示例项目,该项目使用 Storyboard 并仅针对 iOS11。一切正常。 只是不要忘记设置标签的约束条件 - 顶部、底部、前导和尾随。自动调整单元格需要这些约束。最后,将 UILabel
的行数设置为 0。
将 垂直内容拥抱优先级 增加 1 UILabel
当所有其他方法都失败时,请尝试将内容压缩阻力优先级设置为 1000。这就是我解决问题的方法。