【转】自定义UITableViewCell(registerNib: 与 registerClass: 的区别)

时间:2023-03-08 21:03:41
【转】自定义UITableViewCell(registerNib: 与 registerClass: 的区别)

自定义UITableViewCell大致有两类方法:

<一>使用nib

1、xib中指定cell的Class为自定义cell类型(注意不是设置File's Owner的class)

【转】自定义UITableViewCell(registerNib: 与 registerClass: 的区别)

2、调用 tableView 的 registerNib:forCellReuseIdentifier:方法向数据源注册cell

[_tableView registerNib:[UINib nibWithNibName:@"xxxxxCell" bundle:nil] forCellReuseIdentifier:kCellIdentify];

3、在cellForRowAtIndexPath中使用dequeueReuseableCellWithIdentifier:forIndexPath:获取重用的cell,若无重用的cell,将自动使用所提供的nib文件创建cell并返回(若使用旧式dequeueReuseableCellWithIdentifier:方法需要判断返回是否为空而进行新建)

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

4、获取cell时若无可重用cell,将创建新的cell并调用其中的awakeFromNib方法,可通过重写这个方法添加更多页面内容

<二>不使用nib

1、重写自定义cell的initWithStyle:withReuseableCellIdentifier:方法进行布局

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self)
{
// cell页面布局
[self setupView];
}
return self;
}

2、为tableView注册cell,使用registerClass:forCellReuseIdentifier:方法注册(注意是Class)

[_tableView registerClass:[xxxxxCell class] forCellReuseIdentifier:kCellIdentify];

3、在cellForRowAtIndexPath中使用dequeueReuseableCellWithIdentifier:forIndexPath:获取重用的cell,若无重用的cell,将自动使用所提供的class类创建cell并返回

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

4、获取cell时若无可重用cell,将调用cell中的initWithStyle:withReuseableCellIdentifier:方法创建新的cell

另外要注意的:

1、dequeueReuseableCellWithIdentifier:与dequeueReuseableCellWithIdentifier:forIndexPath:的区别:

前者不必向tableView注册cell的Identifier,但需要判断获取的cell是否为nil;

后者则必须向table注册cell,可省略判断获取的cell是否为空,因为无可复用cell时runtime将使用注册时提供的资源去新建一个cell并返回

2、自定义cell时,记得将其他内容加到self.contentView 上,而不是直接添加到 cell 本身上

另外:

registerClass是iOS6新加的

iOS6新增了这个方法

dequeueReusableCellWithIdentifier:forIndexPath:

而以前是这个

dequeueReusableCellWithIdentifier:

在此之前cell的重用写法是

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

而之后多了这种写法

static NSString *ID = @"cell";
[self.tableView registerClass:[MyCell class] forCellReuseIdentifier:ID];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];

区别在于之前的写法取出重用cell的时候可能是空的

而后来的写法如果取出空的那就自动创建一个新的 register就是告诉它创建个什么样的

总结:

1.自定义cell时,

若使用nib,使用 registerNib: 注册,dequeue时会调用 cell 的 -(void)awakeFromNib

不使用nib,使用 registerClass: 注册, dequeue时会调用 cell 的 - (id)initWithStyle:withReuseableCellIdentifier:

2.需不需要注册?

使用dequeueReuseableCellWithIdentifier:可不注册,但是必须对获取回来的cell进行判断是否为空,若空则手动创建新的cell;

使用dequeueReuseableCellWithIdentifier:forIndexPath:必须注册,但返回的cell可省略空值判断的步骤。

【转】自定义UITableViewCell(registerNib: 与 registerClass: 的区别)