UITableView 加载cell 的几种常用方式

开发的过程中,由于经常用到tableview,加载cell,也经常忘记所有,记录下经常用的几种方式
1 代码加载cell

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *idfity=[NSString stringWithFormat:@"%ld%ld",(long)indexPath.section,(long)indexPath.row];
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:idfity];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:0 reuseIdentifier:idfity];

    }
    return cell;
}

这种经常用的方式,也是最早开始用的方式,加载比较麻烦,代码量比较多;

2 tableview registerClass 的方式加载
首先在viewdidload 方法注册cell

 [tableView registerClass:[TableViewCell class] forCellReuseIdentifier:IDENTIFIER];

然后

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];
  //这里会发现,cell一直都不是nil,不再需要创建
    if (cell == nil) {
    }
    return cell; 
}

这样创建cell的方式,cell 不会为空,所有也不需要判断cell==nil 的代码了,

3 通过xib 文件加载cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* cell = nil;
    cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:nil options:nil].firstObject;
    }

    return cell; 
}

这样加载和第一种代码加载的结果一样,cell 开始是空的,一屏幕划过去后,cell 就不会加载后,不会为空,开始重用,

4 用注册的方式加载xib 文件

 [tableView registerNib:[UINib nibWithNibName:@"TableViewCell" bundle:nil] forCellReuseIdentifier:IDENTIFIER];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* cell = nil;
    cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];
    if (cell == nil) {
   //cell一直都不是nil,不再需要创建,所有也不需要判断为空了
    }
    return cell; 
}

这种和第第二种代码注册结果是一样的,

5 通过storyboard 创建的tableview cell 加载方式

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XXXTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"XXXTableViewCell"];
    [cell updateView:receiver];
    return cell;
}

sb 创建更简单化了cell 的加载方式

以上就是cell 加载的几种方式,又不对的地方还望指正,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值