Reputation: 5169
I'm new to iOS and I'm having issues with adding/removing a cell accessoryTypeCheckmark when a user selects a cell. I have a friends list in a UITableView and the user should be able to select multiple friends and have a checkmark appear next to them. If the user taps on a friend that has already been selected, the checkmark should disappear. I am keeping track of the friends that have been selected in a NSMutableArray titled 'friends_selected'.
I have the cellForRowAtIndex path set up to check if the friends_selected array contains the username, and if so add a checkmark.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
FriendsListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.usernameID.text = [self.friends_username objectAtIndex:indexPath.row];
if ([self.friends_selected containsObject:cell.usernameID.text]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
In my didSelectRowAtIndexPath I am adding or removing the username from the friends_selected array and reloading the table data.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
FriendsListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.usernameID.text = [self.friends_username objectAtIndex:indexPath.row];
if ([self.friends_selected containsObject:cell.usernameID.text]) {
[self.friends_selected removeObject:cell.usernameID.text];
}
else {
[self.friends_selected addObject:cell.usernameID.text];
}
[tableView reloadData];
}
Right now the friends_selected array is correctly updating with which usernames have been selected or deselected. There are no checkmarks appearing, however the cell will become highlighted when selected and will remain highlighted even if unselected. Any help would be great, I've been stuck all day on this issue that seems like a simple solution.
Upvotes: 0
Views: 83
Reputation: 318834
In your didSelectRow...
method you should replace:
FriendsListCell *cell = (FriendsListCell *)[tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
with:
FriendsListCell *cell = (FriendsListCell *)[tableView cellForRowAtIndexPath:indexPath];
You don't want a new cell, you want the actual cell for the selected row.
And do not call reloadData
too. Either update the cell directly or just call reloadData
, not both.
Upvotes: 2