iOS笔记-自定义cell的重用

一、使用xib

<1>不需要注册

直接在-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;方法中写就好了

static NSString *identifer=@"****TableViewCell";

****TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];

if (cell == nil) {

        cell = [[[NSBundle mainBundle] loadNibNamed:@"****TableViewCell" owner:self options:nil] lastObject];

 }

<2>需要注册

1、在- (void)viewDidLoad;方法中注册:

[_tableView registerNib:[UINib nibWithNibName:@"****TableViewCell" bundle:nil] forCellReuseIdentifier:@"****TableViewCell"];

2、在-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;方法中写:

static NSString *identifer=@"****TableViewCell";

HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer forIndexPath:indexPath];


二、纯代码

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>、

1、需要注册

为tableView注册cell,使用registerClass:forCellReuseIdentifier:方法注册

[_tableView registerClass:[****TableViewCell class] forCellReuseIdentifier:@"****TableViewCell"];

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

****TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer forIndexPath:indexPath];

2、不需要注册

static NSString *identifer=@"****TableViewCell";

****TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];

if (cell == nil) {

cell = [[****TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];

}


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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容