iOS中创建UITableViewCell的正确姿态

从iOS6开始,创建cell有了新的重用方法dequeueReusableCellWithIdentifier,创建cell通常都在数据源方法中这么写:

 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"Section:%ld Row:%ld",indexPath.section,indexPath.row];

但在苹果自带的tableview中,重用方法“dequeueReusableCellWithIdentifier:forIndexPath:”带了indexPath参数,当然按照以前的写法删掉参数再判断if(cell == nil) 也是可以的,但总觉得不好,这时候同样是iOS6的新方法 “ registerClass:forCellReuseIdentifier:(如果用到了xib,注册方法为:registerNib:forCellReuseIdentifier:)” 派上了用场,这样的话创建cell就可以这样:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellId];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.textLabel.text = [NSString stringWithFormat:@"Section:%ld Row:%ld",indexPath.section,indexPath.row];

    return cell;
}

这样的话没有了if(cell == nil)的判断,但有时候总觉得不放心,加上原来的判断后打上断点会发现,cell永远不等于nil, 所以对于注册过的cell来说,判断是否为空已经没意义了。虽然实际上大多数cell都是用自定义类型,但倘若的确要使用系统的UITableViewCell并更改UITableViewCellStyle的话,还得用老方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值