TableView复用Cell数量之谜

偶然发现一个现象,跟预期不太一样。

如论如何设置Tableview的行高,它创建的用于的复用Cell数量是恒定的。

那么这是什么情况呢?

  • 行高为100时


    Simulator Screen Shot - iPhone 11 - 2020-06-10 at 16.42.37.png
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: Self.ID)
        if cell == nil {
            cell = MyTableViewCell(style: .default, reuseIdentifier: Self.ID)
            print("indexPath.row + \(indexPath.row)")
        }
        cell!.textLabel?.text = "\(indexPath.row)"
        return cell!
 }


// tableView.rowHeight = 100.0
控制台输出结果:
indexPath.row + 0
indexPath.row + 1
indexPath.row + 2
indexPath.row + 3
indexPath.row + 4
indexPath.row + 5
indexPath.row + 6
indexPath.row + 7
indexPath.row + 8
indexPath.row + 9
indexPath.row + 10
indexPath.row + 11
indexPath.row + 12
indexPath.row + 13
indexPath.row + 14
indexPath.row + 15
indexPath.row + 16
indexPath.row + 17
indexPath.row + 18
indexPath.row + 19
  • 行高为200时


    Simulator Screen Shot - iPhone 11 - 2020-06-10 at 16.42.28.png
// tableView.rowHeight = 200.0
控制台输出结果:
indexPath.row + 0
indexPath.row + 1
indexPath.row + 2
indexPath.row + 3
indexPath.row + 4
indexPath.row + 5
indexPath.row + 6
indexPath.row + 7
indexPath.row + 8
indexPath.row + 9
indexPath.row + 10
indexPath.row + 11
indexPath.row + 12
indexPath.row + 13
indexPath.row + 14
indexPath.row + 15
indexPath.row + 16
indexPath.row + 17
indexPath.row + 18
indexPath.row + 19
  • 不设置行高时,也就是默认行高为44


    Simulator Screen Shot - iPhone 11 - 2020-06-10 at 16.42.42.png
// tableView.rowHeight = 44
控制台输出结果:
indexPath.row + 0
indexPath.row + 1
indexPath.row + 2
indexPath.row + 3
indexPath.row + 4
indexPath.row + 5
indexPath.row + 6
indexPath.row + 7
indexPath.row + 8
indexPath.row + 9
indexPath.row + 10
indexPath.row + 11
indexPath.row + 12
indexPath.row + 13
indexPath.row + 14
indexPath.row + 15
indexPath.row + 16
indexPath.row + 17
indexPath.row + 18
indexPath.row + 19

到这里是不是恍然大悟了。。。

结论

UITableView的复用机制所创建的Cell数量不随自定义的行高而改变,而是恒定的数值。
即在默认行高下,整个屏幕所能展示的最多Cell的数量,🉑️根据屏幕高度与默认行高的比值计算得出!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。