现在的位置: 首页 > 综合 > 正文

解析UITableViewCell的reuse问题

2013年09月04日 ⁄ 综合 ⁄ 共 1567字 ⁄ 字号 评论关闭

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。


抱歉!评论已关闭.