【问题标题】:Reuse Custom Cell using NIB使用 NIB 重用自定义单元
【发布时间】:2012-08-07 00:54:23
【问题描述】:

您好,我是 IOS 开发新手,我创建了一个 UITableView,它使用在 nib 中创建的自定义单元格。下面是我的ViewController 中的代码,它正在加载单元格,但是如果我上下滚动 3 次,应用程序就会崩溃,因为我认为我没有正确地重用单元格。我四处搜索,但我发现的大部分代码/解决方案似乎已经过时了。我的代码在下面,任何帮助都非常感谢!

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CustomCell";
    CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        for (id currentObject in topLevelObjects){
            if ([currentObject isKindOfClass:[UITableViewCell class]]){
                cell =  (CustomCell *) currentObject;
                break;
            }
        }
    }
    cell.TITLE.text = [NSString stringWithFormat:@"\"%@\"", [TITLE objectAtIndex:indexPath.row]];
    cell.desc.text = [desc objectAtIndex:indexPath.row];
    cell.votes.text = [votes objectAtIndex:indexPath.row];
    return cell;
}

【问题讨论】:

    标签: ios uitableview nib recycle


    【解决方案1】:

    您可以为tableView注册笔尖,例如:

    (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *cellIdentifier = @"CustomCell";
        CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            [tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
            cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        }
    
        //...
    
        return cell;
    }
    

    【讨论】:

      【解决方案2】:

      换行

      CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];  
      

      成为

      CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier: CellIdentifier];  
      

      转到您在 IB 中的 CustomCell .xib 文件,查找 identifier 字段并将其设置为 CustomCell

      【讨论】:

      • 我使用与上面建议的代码相同的代码,但如果我在 nib 文件中设置单元格标识符,那么当我上下滚动时,标签上的控件就会消失。但是,如果我跳过在 nib 中设置标识符,则表格视图滚动非常慢,但数据会正确显示。任何想法可能是什么问题?
      • 首先,如果您跳过设置标识符,tableview 将滚动缓慢,因为您不重复使用单元格,并且每个单元格及其子视图都会重新创建。我猜你的问题是你没有在 cellForRowAtIndexPath 方法中正确配置你的单元格。确保更新单元格数据的所有代码都在 if(cell == nil) 语句之外。因为如果您使用标识符,则单元格会被重用,并且不会调用 if(cell == nil) 语句中的代码。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多