uitableviewxcode4.2didselectrowatindexpath

UITAbleView cell selection affect another UITableView cell in same UITableView


I am developing an iPhone application with UITableView. I have implemented a check mark on each cell with didSelectRowAtIndexPath delegate.

Now I want to select a cell that disable all other cells (remove the check marks) and vice versa (eg: to select 8th cell that shows the check mark on 8th cell and remove the check mark of other cells, then select other cell shows the check mark on that cell and remove the check mark on 8th cell).

How to implement this in UITableView?


Solution

  • You can achieve this by adding these two ivars to your UITableViewController class to track which cell is currently checked:

    NSInteger currentlyCheckedRow;
    NSInteger currentlyCheckedSection;
    

    In your initialize method, set currentlyCheckedRow and currentlyCheckedSection to a negative integer such as -1 so that it is not matched by any possible row value.

    Add the following to your -tableView:cellForRowAtIndexPath: method:

    // determine if cell should have checkmark
    cell.accessoryType = UITableViewCellAccessoryNone;
    if ( (indexPath.row == currentlyCheckedRow) &&
         (indexPath.section == currentlyCheckedSection) )
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    };
    

    Update the currentlyCheckedRow ivar when -tableView:didSelectRowAtIndexPath: is called:

     currentlyCheckedRow = indexPath.row;
     currentlyCheckedSection = indexPath.section;
     [tableView reloadData];