UITableView中有两种重用Cell的方法:ide
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier; - (id)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);
在iOS 6中dequeueReusableCellWithIdentifier:被dequeueReusableCellWithIdentifier:forIndexPath:所取代。如此一来,在表格视图中建立并添加UITableViewCell对象会变得更为精简而流畅。并且使用dequeueReusableCellWithIdentifier:forIndexPath:必定会返回cell,系统在默认没有cell可复用的时候会自动建立一个新的cell出来。布局
使用dequeueReusableCellWithIdentifier:forIndexPath:的话,必须和下面的两个配套方法配合起来使用:spa
// Beginning in iOS 6, clients can register a nib or class for each cell. // If all reuse identifiers are registered, use the newer -dequeueReusableCellWithIdentifier:forIndexPath: to guarantee that a cell instance is returned. // Instances returned from the new dequeue method will also be properly sized when they are returned. - (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0); - (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);
一、若是是用NIB自定义了一个Cell,那么就调用registerNib:forCellReuseIdentifier:code
二、若是是用代码自定义了一个Cell,那么就调用registerClass:forCellReuseIdentifier:对象
以上这两个方法能够在建立UITableView的时候进行调用。blog
这样在tableView:cellForRowAtIndexPath:方法中就能够省掉下面这些代码:string
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; it
if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; }
取而代之的是下面这句代码:table
1、使用NIBclass
一、xib中指定cell的Class为自定义cell的类型(不是设置File's Owner的Class)
二、调用registerNib:forCellReuseIdentifier:向数据源注册cell
[_tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:kCellIdentify];
三、在tableView:cellForRowAtIndexPath:中使用dequeueReusableCellWithIdentifier:forIndexPath:获取重用的cell,若是没有重用的cell,将自动使用提供的nib文件建立cell并返回(若是使用dequeueReusableCellWithIdentifier:须要判断返回的是否为空)
四、获取cell时若是没有可重用cell,将建立新的cell并调用其中的awakeFromNib方法
2、不使用NIB
一、重写自定义cell的initWithStyle:withReuseableCellIdentifier:方法进行布局
二、注册cell
[_tableView registerClass:[CustomCell class] forCellReuseIdentifier:kCellIdentify];
三、在tableView:cellForRowAtIndexPath:中使用dequeueReusableCellWithIdentifier:forIndexPath:获取重用的cell,若是没有重用的cell,将自动使用提供的class类建立cell并返回
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];
四、获取cell时若是没有可重用的cell,将调用cell中的initWithStyle:withReuseableCellIdentifier:方法建立新的cell