Cell自定义registerNib:与registerClass:

向右看齐 2023-10-17 14:10 93阅读 0赞

一、使用Nib

registerNib: forCellReuseIdentifier:方法向数据源注册cell

  1. [self.table registerNib:[UINib nibWithNibName:@"xxCell" bundle:nil] forCellReuseIdentifier:CellIdentify];

在cellForRowAtIndexPath中使用dequeueReuseableCellWithIdentifier: forIndexPath:获取重用的cell,若无重用的cell,将自动使用所提供的nib文件创建cell并返回

  1. xxCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentify forIndexPath:indexPath];

获取cell时若无可重用cell,将创建新的cell并调用其中的 awakeFromNib 方法,可通过重写这个方法进行页面布局

二、不使用Nib

registerClass: forCellReuseIdentifier:方法注册

  1. [self.table registerClass:[xxCell class] forCellReuseIdentifier:CellIdentify];

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

  1. - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
  2. {
  3. self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
  4. if (self)
  5. {
  6. [self setSubView]; //cell页面UI
  7. }
  8. return self;
  9. }

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

  1. xxCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentify forIndexPath:indexPath];

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

三、总结如下:

1、自定义cell

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

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

2、自定义的cell需不需要注册

使用dequeueReuseableCellWithIdentifier: 无需注册,但是必须对cell进行判空,若空则创建新的cell;

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

发表评论

表情:
评论列表 (有 0 条评论,93人围观)

还没有评论,来说两句吧...

相关阅读