iOS框架 底层 技巧UIKitInterview

UITableView的两种重用Cell方法的区别

2017-07-08  本文已影响38人  泼茶_

壹: 写在前面

在使用UITableView的时候, 需要面临两种重用Cell方法的选择, 这就需要了解什么时候使用什么方法, 以及两种方法到底做了什么.

贰: 区别

在iOS 6中dequeueReusableCellWithIdentifier:dequeueReusableCellWithIdentifier:forIndexPath:所取代。

如此一来,dequeueReusableCellWithIdentifier:forIndexPath:在表格视图中创建并添加UITableViewCell对象会变得更为精简而流畅。

dequeueReusableCellWithIdentifier:forIndexPath:一定会返回cell,系统在默认没有cell可复用的时候会自动创建一个新的cell出来

叁: dequeueReusableCellWithIdentifier:forIndexPath:的使用:

// 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);

static NSString *CellIdentifier = @"Cell";
 if (cell == nil){
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

肆: More:

tableView:cellForRowAtIndexPath:中使用dequeueReusableCellWithIdentifier:forIndexPath:获取重用的cell,如果没有重用的cell,将自动使用提供的class类创建cell并返回

CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];

获取cell时如果没有可重用的cell,将调用cell中的initWithStyle:withReuseableCellIdentifier:方法创建新的cell

上一篇 下一篇

猜你喜欢

热点阅读