UITableView 正确需要 cell=nil 到 return 个单元格

UITableView needs cell=nil to return cells correctly

我的表格视图由 JSON NSURLSession 创建的新数组填充。数组更新正确,但单元格更新不正确。我正在使用包含标签 1、2 和 3 的水平堆栈视图。

无论第一个表视图显示为三个标签(假设它显示在第 0 行,“A B C”),然后当我 select 通过 JSON 进行新搜索时,标签 1-3 更新为“D E F”,表视图 return 是第一个视图(“A B C”)的单元格,然后如果有更多行,这些行将正常显示。如果我return到JSON中的原始搜索,就会出现正确的tableview。

我必须在

之后立即输入 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];

第二种方法永远不会returnsnil。这只是其众多优势之一。你应该永远不要调用第一个方法;第二个取代它。