UITableView中有两种重用Cell的方法:
- 1
- 2
- 1
- 2
在iOS 6中dequeueReusableCellWithIdentifier:
被dequeueReusableCellWithIdentifier:forIndexPath:
所取代。如此一来,在表格视图中创建并添加UITableViewCell对象会变得更为精简而流畅。而且使用dequeueReusableCellWithIdentifier:forIndexPath:一定会返回cell,系统在默认没有cell可复用的时候会自动创建一个新的cell出来。
使用 dequeueReusableCellWithIdentifier:forIndexPath:
的话,必须和下面的两个配套方法配合起来使用:
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
1、如果是用NIB自定义了一个Cell,那么就调用registerNib:forCellReuseIdentifier:
2、如果是用代码自定义了一个Cell,那么就调用 registerClass:forCellReuseIdentifier:
以上这两个方法可以在创建UITableView的时候进行调用。
这样在tableView:cellForRowAtIndexPath:
方法中就可以省掉下面这些代码:
- 1
- 2
- 3
- 1
- 2
- 3
取而代之的是下面这句代码
- 1
- 1
一、使用NIB
1、xib中指定cell的Class为自定义cell的类型(不是设置File’s Owner的Class)
2、调用registerNib:forCellReuseIdentifier:
向数据源注册cell
- 1
- 1
3、在tableView:cellForRowAtIndexPath:
中使用dequeueReusableCellWithIdentifier:forIndexPath:
获取重用的cell,如果没有重用的cell,将自动使用提供的nib文件创建cell并返回(如果使用dequeueReusableCellWithIdentifier:
需要判断返回的是否为空)
- 1
- 1
4、获取cell时如果没有可重用cell,将创建新的cell并调用其中的awakeFromNib
方法
二、不使用NIB
1、重写自定义cell的initWithStyle:withReuseableCellIdentifier:
方法进行布局 【自定义tableviewcell类】
2、注册cell【_tableview是uitableview对象】
- 1
- 1
3、在tableView:cellForRowAtIndexPath:
中使用dequeueReusableCellWithIdentifier:forIndexPath:
获取重用的cell,如果没有重用的cell,将自动使用提供的class类创建cell并返回
- 1
- 1
4、获取cell时如果没有可重用的cell,将调用cell中的initWithStyle:withReuseableCellIdentifier:
方法创建新的cell
另外:cell的prepareForReuse方法:在cell每次复用之前,对其进行一次reset操作
这个操作一般都是UI相关的,而非数据
工作流是这样的:
tableView:cellForRowAtIndexPath:中调用 dequeueReusableCellWithIdentifier:--->cell从复用池中被取出--->prepareForReuse(reset UI)--->新数据get---> 展示数据