解析UITableViewCell的reuse问题

UITableView在iOS开发中会经常使用,对于行数很多的UITableView,可以通过UITableViewCell的重用,来保证执行效率。源码下载点击这里

我们通过代码来探索UITableViewCell重用的实现,下面是一段使用UITableView的代码,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *CellIdentifier = @"myCell";
    //NSString *CellIdentifier = [NSString stringWithFormat:@"myCell_%d",indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:@"myCell"];
        UITextField *tf;
        tf = [[UITextField alloc] initWithFrame:CGRectMake(100, 10, 150, 40) ];
        tf.delegate = self;
        tf.borderStyle = UITextBorderStyleRoundedRect;
        [cell  addSubview:tf];
        [tf release];
        
        
    }
    // Configure the cell...
    cell.textLabel.text = [NSString stringWithFormat:@"%d",indexPath.row];
    
    return cell;
}

运行结果是这样


我们在textfield里输入label的序号,然而我们上下拖动后,结果是textfield的值并没有得到保存,其随着cell的重用而变化。


我们回到dequeueReusableCellWithIdentifier的定义

- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier;  // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
使用委托来获取一个已经分配的cell,代替分配新的一个;在这个例子中,将当前屏幕下创建的Cell都先加入到对象池,这是对象池的內Cell的个数大致是8,当我们滑动TableView时,将使用 dequeueReusableCellWithIdentifier方法返回对象,该方法通过

reuseIdentifier(“myCell”)在对象池中,查找之前已经放入的cell对象。

然后从对象池中,取出之前放入的,然后执行

    // Configure the cell...
    cell.textLabel.text = [NSString stringWithFormat:@"%d",indexPath.row];

所以我们需要为textfield里的text内容设置model层,然后配置 textfield的内容,像我们对textLabel的设置一样

还有了不完美的解决方案,既然它重用出问题,就不让它重用,代码如下

NSString *CellIdentifier = [NSString stringWithFormat:@"myCell_%d",indexPath.row];
对于每一行,设定不同的reuseIdentifier。





  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值