Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly toggle UITableViewCell's accesoryType on cell selection/deselection?

I'm trying to toggle accesoryType when a table cell is selected/deselected... the behavior should be: tap -> set accessoryType to UITableViewCellAccessoryCheckmark -> tap the cell again -> rollback to UITableViewCellAccessoryNone type. The implementation in my controller is the following:

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{   
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setAccessoryType:UITableViewCellAccessoryNone];
}

...anyway once the style is configured as UITableViewCellAccessoryCheckmark I'm unable to restore it back to UITableViewCellAccessoryNone! I also tried to call:

[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];

but does not remove the checkmark... what should I do?

EDIT: The implementation is ok, the problem was in the custom UITableViewCell subclass... sorry :P

like image 800
daveoncode Avatar asked Dec 06 '22 17:12

daveoncode


2 Answers

Try this if this is what you want

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    {   
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        else
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }
like image 56
X Slash Avatar answered Mar 15 '23 23:03

X Slash


If you want to have only one row as checkmark use this

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = (cell.accessoryType == UITableViewCellAccessoryCheckmark) ? UITableViewCellAccessoryNone : UITableViewCellAccessoryCheckmark;
    if (_lastSelectedIndexPath != nil)
    {
        UITableViewCell *lastSelectedCell = [tableView cellForRowAtIndexPath:_lastSelectedIndexPath];
        lastSelectedCell.accessoryType = UITableViewCellAccessoryNone;
    }
    _lastSelectedIndexPath = indexPath;
} 
like image 31
Sal Avatar answered Mar 16 '23 00:03

Sal