iOS 8 中的新增功能,您只需设置估计行高即可获得 100% 动态表格视图单元格,然后使用自动布局在单元格中布局元素。如果内容的高度增加,单元格的高度也会增加。这非常有用,我想知道表视图中的节标题是否可以实现相同的功能?
例如,可以创建一个UIView
in tableView:viewForHeaderInSection:
, add a UILabel
子视图,为视图指定标签的自动布局约束,并增加视图的高度以适应标签的内容,而无需实现tableView:heightForHeaderInSection:
?
的文档viewForHeaderInSection
状态:“只有当 tableView:heightForHeaderInSection: 也实现时,此方法才能正常工作。”我还没有听说 iOS 8 是否有任何改变。
如果做不到这一点,模仿这种行为的最佳方法是什么?
这个有可能。它是与 iOS 8 中引入的动态单元格高度一起推出的新功能。
为此,请对节标题高度使用自动尺寸标注,如果需要,您可以提供估计的节标题高度。当选择表视图时或以编程方式可以在 Interface Builder 中完成此操作:
tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 38
//You can use tableView(_:heightForHeaderInSection:) and tableView(_:estimatedHeightForHeaderInSection:)
//if you need to support different types of headers per section
然后实施tableView(_:viewForHeaderInSection:)
并使用自动布局根据需要约束视图。确保完全约束UITableViewHeaderFooterView
's contentView
,尤其是从上到下,因此高度可以由约束确定。就是这样!
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UITableViewHeaderFooterView()
headerView.translatesAutoresizingMaskIntoConstraints = false
headerView.backgroundView = {
let view = UIView()
view.backgroundColor = myCustomColor
return view
}()
let headerLabel = UILabel()
headerLabel.translatesAutoresizingMaskIntoConstraints = false
headerLabel.text = "Hello World"
headerView.contentView.addSubview(headerLabel)
NSLayoutConstraint.activate([
headerLabel.leadingAnchor.constraint(equalTo: headerView.contentView.leadingAnchor, constant: 16),
headerLabel.trailingAnchor.constraint(equalTo: headerView.contentView.trailingAnchor, constant: -16),
headerLabel.topAnchor.constraint(equalTo: headerView.contentView.topAnchor, constant: 12),
headerLabel.bottomAnchor.constraint(equalTo: headerView.contentView.bottomAnchor, constant: -12)
])
return headerView
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)