UITableView需要cell = nil才能正确返回单元格

问题描述

我的表格视图是根据JSON NSURLSession创建的新数组填充的。阵列正确更新,但是单元未正确更新。我正在使用包含Labels1、2和3的水平Stackview。

无论显示的第一个表格视图是什么(三个行都显示在第0行“ ABC”中),然后当我通过JSON选择新搜索时,标签1-3更新为“ DEF” tableview返回第一个视图(“ ABC”)的单元格,然后如果有更多行,则这些行将正常显示。如果我以JSON返回原始搜索,则会显示正确的表格视图。

我必须在

之后立即输入cell = nil

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
cell=nil;  //have to add this line for the cells to return correctly

if (cell == nil)
    {
    UILabel *label1 = [UILabel new];
    UILabel *label2 = [UILabel new];
    UILabel *label2 = [UILabel new];
    label1.textAlignment = NSTextAlignmentCenter;
    label2.textAlignment = NSTextAlignmentCenter;
    label3.textAlignment = NSTextAlignmentCenter;

     UIStackView *stackView = [[UIStackView alloc] initWithArrangedSubviews: @[label1,label2,label3]];
    
    stackView.axis = UILayoutConstraintAxisHorizontal;
    stackView.distribution = UIStackViewdistributionFillEqually;
        
    [cell.contentView addSubview: stackView];
    
    stackView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [stackView.centerYAnchor constraintEqualToAnchor: cell.contentView.centerYAnchor].active = YES;
    [stackView.leadingAnchor constraintEqualToAnchor: cell.contentView.leadingAnchor constant: 10].active = YES;
    [stackView.trailingAnchor constraintEqualToAnchor: cell.contentView.trailingAnchor constant: -10].active = YES;

     }
    
label1.text = self.data[indexPath.row][0];
label1.text = self.data[indexPath.row][0];
label1.text = self.data[indexPath.row][0];

return cell;
}

我的其他表视图不需要。我在这里做什么错了?

解决方法

您不小心调用了错误的方法:

cell = [tableView dequeueReusableCellWithIdentifier:cellID];

您想要这个:

UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath: indexPath];

第二种方法从不返回nil。这只是其众多优势之一。您应该从不调用第一个方法;第二个取代它。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...