Weakman10122 Weakman10122 - 4 months ago 21
iOS Question

iOS UITableView : Set the correct cell as selected when tableview data changes

This is a little hard to explain, but I will try my best. The code below is just some simple code I put together to demonstrate my problem better. When a user selects the second cell (row) for example, the tableview properly changes the cell with this

[cell selected:YES];
when tableview reloads. If the second cell is selected and my tableview reloads with more new cells, the wrong cell is selected. The previous selected second cell becomes the fourth or fifth cell when the tableview updates, but the second cell is still selected.

I know this is because of
selectIndexPath
index row is two. Is there a way around this?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
FriendCell *cell

if (selectedIndexPath.row == indexPath.row )
[cell selected:YES];
else
[cell selected:NO];

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
selectIndexPath = indexPath;
}

Answer

If your source array can changed (add/remove elements) then you have to keep track of the selected item, not the selected index. You haven't shown what your data source object is, but let's say it was an array of strings:

@property (strong,nonatomic) NSMutableArray *tableData;
@property (strong,nonatomic) NSString *selectedItem;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
   FriendCell *cell

   if (self.selectedItem != nil && [self.tableData[indexPath.row] isEqualToString:self.selectedItem]) {
     [cell selected:YES];
   } else {
     [cell selected:NO];
   }

  return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.selectedItem = self.tableData[indexPath.row];
}
Comments