Search code examples
xcodeuitableviewstackview

UITableView needs cell=nil to return cells correctly


My tableview fills from a new array created from a JSON NSURLSession. The array updates correctly, but the cell does not update correctly. I am using a horizontal stackview containing Labels1, 2 and 3.

Whatever is the first tableview displayed (lets say it shows in row 0, "A B C") as the three labels, then when I select a new search through the JSON, and the labels 1-3 update to "D E F" the tableview returns the cell(s) of the first view ("A B C") and then if there are more rows, those appear normally. If I return to the original search in JSON, the correct tableview appears.

I have to enter cell=nil right after the

- (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;
}

My other tableviews don't require that. What am I doing wrong here?


Solution

  • You've accidentally called the wrong method:

    cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    

    You wanted this:

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

    The second method never returns nil. That's just one of its many advantages. You should never call the first method; the second one supersedes it.