【问题标题】:UITableView needs cell=nil to return cells correctlyUITableView 需要 cell=nil 才能正确返回单元格
【发布时间】:2020-10-09 23:08:40
【问题描述】:

我的 tableview 从一个 JSON NSURLSession 创建的新数组中填充。数组正确更新,但单元格未正确更新。我正在使用包含 Labels1、2 和 3 的水平堆栈视图。

无论显示的第一个表视图是什么(假设它显示在第 0 行,“A B C”)作为三个标签,然后当我通过 JSON 选择新搜索时,标签 1-3 更新为“D E F” tableview 返回第一个视图的单元格(“A B C”),然后如果有更多行,它们会正常显示。如果我返回到 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;
}

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

【问题讨论】:

    标签: xcode uitableview stackview


    【解决方案1】:

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

    cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    

    你想要这个:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 2013-12-24
      • 2016-12-27
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      相关资源
      最近更新 更多