gpt4 book ai didi

ios - 是否可以使用自动布局获取动态表格 View 部分标题高度?

转载 作者:IT王子 更新时间:2023-10-29 07:29:23 25 4
gpt4 key购买 nike

iOS 8 中的新功能,您只需设置估计行高即可获得 100% 动态表格 View 单元格,然后使用自动布局在单元格中布局元素。如果内容的高度增加,单元格的高度也会增加。这非常有用,我想知道是否可以对 TableView 中的节标题完成同样的壮举?

例如,能否在 tableView:viewForHeaderInSection: 中创建一个 UIView,添加一个 UILabel subview ,为针对 View 添加标签,并让 View 增加高度以适应标签的内容,而无需实现 tableView:heightForHeaderInSection:?

viewForHeaderInSection 的文档指出:“此方法只有在 tableView:heightForHeaderInSection: 也已实现时才能正常工作。”我还没有听说 iOS 8 是否有任何变化。

如果不能做到这一点,模仿这种行为的最佳方式是什么?

最佳答案

这是可能的。它是与 iOS 8 中引入的动态单元格高度一起新增的。

为此,请为部分标题高度使用自动尺寸,如果需要,您可以提供估计的部分标题高度。这可以在选择 TableView 时在 Interface Builder 中完成或以编程方式完成:

Table view configuration in storyboard

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:) 并根据需要使用自动布局来约束 View 。确保完全约束到 UITableViewHeaderFooterViewcontentView,尤其是从上到下,这样高度就可以由约束来确定。就是这样!

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
}

关于ios - 是否可以使用自动布局获取动态表格 View 部分标题高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29462331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com