手动设置时节标题高度不同

时间:2019-05-31 07:20:09

标签: ios swift uitableview uitableviewsectionheader

我正在尝试更改表格视图内特定节标题的高度。我使用下面的代码进行了测试,只是为了了解INSERT INTO emails_sent (ID, email_dest, sent, MessageID, when) VALUES (455, 'email_not_existing@test.com', TRUE, $messageID, '2019-05-30 8:00:00')的工作原理。

tableView(_:heightForHeaderInSection:)

下面的调试打印显示多次调用该方法,但是标题高度始终为18.0(默认值)。

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    print("DEBUG : ", section, tableView.sectionHeaderHeight)
    return tableView.sectionHeaderHeight
}

现在,当我使用18.0作为返回值的固定值(出于测试目的)时,表视图的垂直扩展在视觉上得到了压缩,这意味着各部分之间的距离更近了,因此整个UI看起来都不同。似乎节之间的空间减少了,因为第一节的标题(垂直)只有一半可见。

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

那怎么可能?
可能是错误吗?

1 个答案:

答案 0 :(得分:1)

As per your code,

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return tableView.sectionHeaderHeight
}

You're returning sectionHeaderHeight as the header height that actually means UITableViewAutomaticDimension.

open var sectionHeaderHeight: CGFloat // default is UITableViewAutomaticDimension

As per Apple,

This nonnegative value is used only if the delegate doesn’t implement the tableView:heightForHeaderInSection: method.

The value you're getting when using print("DEBUG : ", section, tableView.sectionHeaderHeight), i.e. 18.0 is the height of the custom headerView in the .xib.

Still you're getting the proper UI because iOS automatically calculates the header height internally at runtime.

This is the reason your header shrinks when you are passing 18.0 as the header height manually.

In case you want to use separate header height for each section, you need to pass that manually in tableView(_:heightForHeaderInSection:) method, i.e.

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
    }
}

You can add more cases to the above switch statement as per your requirement. Let me know in case you still have any confusion left regarding this.