我正在尝试更改表格 View 中特定部分标题的高度。我用下面的代码进行了测试,只是为了了解 tableView(_:heightForHeaderInSection:)
是如何工作的。
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
print("DEBUG : ", section, tableView.sectionHeaderHeight)
return tableView.sectionHeaderHeight
}
下面的调试打印显示该方法被多次调用,但标题高度始终为 18.0(默认值)。
DEBUG : 4 18.0
DEBUG : 4 18.0
DEBUG : 0 18.0
DEBUG : 0 18.0
DEBUG : 1 18.0
DEBUG : 1 18.0
DEBUG : 2 18.0
...
DEBUG : 3 18.0
现在,只要我使用 18.0 作为返回的固定值(出于测试目的),表格 View 的垂直延伸就会在视觉上被压缩,我认为这些部分靠得更近,因此整个 UI 看起来不同。似乎各部分之间的空间减少了,因为第一部分的标题(垂直)只有一半可见。
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
print("DEBUG : ", section, tableView.sectionHeaderHeight)
return 18.0
}
这怎么可能?
可能是错误?
---更新---(13.06.2019)
我的问题是基于隐藏包含标题的部分 (2) 的意图。我意识到 tableView.sectionHeaderHeight
是使用错误的属性。我应该使用 super.tableView(tableView, heightForHeaderInSection: section)
。
下面的代码可以正常工作:
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if (section == 2) && myCondition {
return CGFloat.leastNonzeroMagnitude
}
return super.tableView(tableView, heightForHeaderInSection: section)
}
不过,我不知道 18.0
(见上文)来自哪里,因为我不使用 .xib 文件。
顺便说一句 super.tableView(tableView, heightForHeaderInSection: section)
总是返回 -1
。我相信这会让 iOS 自行决定选择哪个高度。手动设置 18.0
(用于测试)使标题缩小,因为 iOS 选择的标题高度自动值更高。
我没有找到打印此值的属性(必须在 30.0
左右 - 一个疯狂的猜测,仅此而已)。
最佳答案
根据您的代码,
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return tableView.sectionHeaderHeight
}
您返回 sectionHeaderHeight
作为 header 高度
,这实际上意味着 UITableViewAutomaticDimension
。
open var sectionHeaderHeight: CGFloat // default is UITableViewAutomaticDimension
根据苹果公司的说法,
This nonnegative value is used only if the delegate doesn’t implement the tableView:heightForHeaderInSection: method.
使用 print("DEBUG : ", section, tableView.sectionHeaderHeight)
时得到的值,即 18.0
是 高度
.xib
中的 custom headerView
的 >。
您仍然获得了正确的 UI,因为 iOS
会在运行时
内部自动计算header 高度
。
这就是当您手动传递 18.0
作为 header 高度
时您的 header
缩小的原因。
如果您想为每个部分
使用单独的header height
,您需要在tableView(_ :heightForHeaderInSection:)
方法,即
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
return 50.0
case 1:
return 30.0
default:
return tableView.sectionHeaderHeight
}
}
您可以根据需要向上述switch 语句
添加更多case
。如果您对此仍有任何困惑,请告诉我。
关于ios - 手动设置时节标题高度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56390489/