获取contentSize不准确的原因有几个:

1. tableView没有渲染完成

比如tableView.reloadData()后马上取contentSize肯定不准确,再比如ViewController生命周期还没有走完等。

解决办法:1). 在正确的时机取(看似是废话,但如果你深入了解controller和view生命周期,建议从根本上解决);

                  2). self.view.layoutIfNeeded(),强制layout,然后再获取;

                  3). DispatchQueue.main.asyncAfter个几百毫秒再取(这种方式不利于控制时序,不建议). 

2. tableView使用了自动行高,estimatedRowHeight == UITableViewAutomaticDimension

           可以看到文档中也对estimatedRowHeight对contentOffset和contentSize影响的描述,直接读取的值可能是不正确的.

解决方法:estimatedRowHeight = 0. 有人说我从来没设置过estimatedRowHeight呀,看了文档,The default value is automaticDimension, which means that the table view selects an estimated height to use on your behalf. Set the value to 0 to disable estimated heights. 又有人说,我项目中必须用自适应行高怎么办?那只能重写contentSize计算方式了,或者通过根据数据手动计算contentSize,或者通过别的方式绕过contentSize来满足需求了。

更多推荐

iOS获取TableView的ContentSize不准确及如何准确获取TableView的contentSize