UITableViewCell的注册和初始化

最近在项目开发的过程中,发现和同事就关于UITableViewCell的初始化存在不同之处,在此整理和对比。

不注册 Cell (iOS 6.0 之前都用这个方法)

TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"test"];
if (cell == nil) {
    cell = [[TestTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"test"];
}
return cell;

必须加上if cell == nil的判断

注册nib文件

UITableViewCell的创建时通过xib文件创建的
需要在tableView初始化的时候registerNib

[tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:kCellIdentify]; 

在cellForRowAtIndexPath里就不需要对cell 是否为空进行判断

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

注册代码创建文件

UITableViewCell的创建是通过代码创建的

[tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"];

同理在cellForRowAtIndexPath 里如下

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

两种 dequeueReusableCellWithIdentifier 区别

有 forIndexPath 的方法,需配合 registerClass 或 registerNib使用,并且不需要处理cell为nil的情况

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

相关阅读更多精彩内容

友情链接更多精彩内容