Question

There are couples of wired issue on my UITableView

  1. To change cell background color for those indexPath.row = 0. But some cells are changed also. It looks randomly.
  2. Two methods to create UITableViewCell, but pretty weird is......, too complicated, please see SMFirstViewController.m on github.

  3. prepareForSegue:sender: not works as expected. Weirdly, indexPath = [self.tableView indexPathForCell:sender] sometimes indexPath is null in terms of CELL METHOD 1 or 2

These issues look too complicated, so I upload my code onto github. https://github.com/i0sdev/Temp/tree/segue, SMFirstViewController.m is the file where issues happen.

Pretty appreciated if you could help to fix! Thank you!

Was it helpful?

Solution

Your problem is that you're not accounting for the cell reuse in method 1 (you shouldn't even use method 2). Once your if statement is executed you will make your cell brown, and when that cell gets reused, it will still be brown no matter what indexPath.row it's in. Whenever you set some property of the cell based on the indexPath like you're doing, you need to have an else clause, not just an if.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (indexPath.row == 0)
    {
        cell.backgroundColor = [UIColor brownColor];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
    }else{
        cell.backgroundColor = [UIColor whiteColor];
        cell.textLabel.textAlignment = NSTextAlignmentLeft;
    }
    NSArray * array = [[list objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    cell.textLabel.text = [array valueForKey:@"Number"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"row: %d", indexPath.row];
    
    return cell;
}

As long as you stick with method 1, then the prepareForSegue should work properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top