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

前端 未结 4 1720
野性不改
野性不改 2021-01-03 06:08

I\'m trying to toggle accesoryType when a table cell is selected/deselected... the behavior should be: tap -> set accessoryType to UITableViewCellAc

相关标签:
4条回答
  • 2021-01-03 06:38

    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;
            }
        }
    
    0 讨论(0)
  • 2021-01-03 06:39

    Tapping the cell again equates to selection of the cell and not deselection.

    You need to have a toggle in the - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath method to check if the cell.accessoryType == UITableViewCellAccessoryCheckmark.

    0 讨论(0)
  • 2021-01-03 06:39
    - (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath {
        [theTableView deselectRowAtIndexPath:[theTableView indexPathForSelectedRow] animated:NO];
        UITableViewCell *cell = [theTableView cellForRowAtIndexPath:newIndexPath];
        if (cell.accessoryType == UITableViewCellAccessoryNone) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            // Reflect selection in data model
        } else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
            cell.accessoryType = UITableViewCellAccessoryNone;
            // Reflect deselection in data model
        }
    }
    
    0 讨论(0)
  • 2021-01-03 06:46

    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;
    } 
    
    0 讨论(0)
提交回复
热议问题