首页 > 解决方案 > UITableView contentSize 太大了 10pt(仅限 iOS 10!)

问题描述

我有一个奇怪的问题。我有一个UITableView这样的集合:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 200.0
}

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

func numberOfSections(in tableView: UITableView) -> Int {
     return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if drawerState == .closed {
        return 0
    }
    return 1
}

最初drawerState.closed这样contentSize210。然后我点击一个按钮来改变状态并打印新的内容大小,如下所示:

drawerState = .assessmentOpen
print("old content size is \(tableView.contentSize.height)")
tableView.insertRows(at: [IndexPath(item: 0, section: 0)], with: .none)
print("new content size is \(self.tableView.contentSize.height)") 

我得到的结果是:

old content size is 210.0
new content size is 420.0

新的内容大小比它应该的大 10pt(新的内容大小应该是 410)。这个多余的高度是从哪里来的?奇怪的是,如果我在延迟后再次打印该值是正确的。我已经尝试了所有组合,layoutIfNeeded并且使用DispatchQueue.main.async该值始终比应有的值高 10pt。我究竟做错了什么?注意:它只在 iOS10 上运行,iOS11 没有问题。

标签: iosswiftuitableview

解决方案


如果你有一个.grouped-styled UITableView,那么每个部分的页脚都有一个不为零的默认高度。所以要解决这个问题,请添加:

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return CGFloat.leastNormalMagnitude
}

如果你只返回0. 它回退到默认值。从技术上讲,CGFloat.leastNormalMagnitude它非常类似于0. 但如果你比较它 a0小于CGFloat.leastNormalMagnitude


推荐阅读