UITableView代理和数据源调用的先后顺序规律探究

开篇:因为某些原因和朋友讨论到,tableView在不同的iOS版本中,调用的先后顺序有所不同。特此,我利用相同的代码,在三种版本的模拟器中运行,果然得出了一些特定的规律。

我设置的数据源有1个section、30行,屏幕完全显示为22行。

iOS11.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
numberOfSectionsInTableView
heightForHeaderInSection
heightForFooterInSection (这四个方法一共调用三次,顺序和此列表显示一样)
numberOfRowsInSection

cellForRowAtIndexPath
heightForRowAtIndexPath
….
…. (22-5 = 17行)
heightForHeaderInSection
heightForFooterInSection (在倒数第五行,经测试5是固定的值)
….
cellForRowAtIndexPath
heightForRowAtIndexPath (剩余的5行,和上面的17行是相同的)
….

iOS9.0、iOS10.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
这些方法一共调用三次,顺序和此列表显示一样
numberOfSectionsInTableView
heightForHeaderInSection
heightForHeaderInSection
heightForFooterInSection
heightForFooterInSection
numberOfRowsInSection

heightForRowAtIndexPath
….
…. (30行)
….

cellForRowAtIndexPath
heightForRowAtIndexPath
….
…. (22行)
….
1
2
3
4
5
6
7
8
9
10
11
12
注:
iOS9.0、iOS10.0中
就算以下两个方法都没有实现
self.tableView.sectionHeaderHeight = 20;
self.tableView.sectionFooterHeight = 20;
heightForHeaderInSection和heightForFooterInSection都会调用

iOS11.0中
以下两个方法都没有实现
self.tableView.sectionHeaderHeight = 20;
self.tableView.sectionFooterHeight = 20;
heightForHeaderInSection和heightForFooterInSection不会调用

结语:iOS11.0之后对tableview的数据源调用有了很大改变,节省了很多调用成本。更加合理规范化。
所以如果有同学在获取不到数据源等等问题时,可以考虑本文所写的调用顺序,从而查找原因。

坚持原创技术分享,您的支持将鼓励我继续创作!