问题描述
我的表格视图是根据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
。这只是其众多优势之一。您应该从不调用第一个方法;第二个取代它。