iPhone :UITableView CellAccessory Checkmark

ios picture ios · May 11, 2011 · Viewed 50.3k times · Source

In iPhone App on click of table view cell I want to display Table view cell Accessory type Check mark for that on didSelectRowAtIndexPath i am writing code

if(indexPath.row ==0)
{
[tableView cellForRowAtIndexPath:indexPath].accessoryType=UITableViewCellAccessoryCheckmark;
 }

and displaying check marks.

but in my case i wnt to allow user to check only on cell at a time means if user select other row then that row should checked and previously checked should be unchecked

How can I achieve that?

Answer

idz picture idz · May 11, 2011

Keep track, in an instance variable, of which row is checked. When the user selects a new row, first uncheck the previously checked row, then check the new row and update the instance variable.

Here is more detail. First add a property to keep track of the currently checked row. It's easiest if this is an NSIndexPath.

@interface RootViewController : UITableViewController {
    ...
    NSIndexPath* checkedIndexPath;
    ...
}

...
@property (nonatomic, retain) NSIndexPath* checkedIndexPath;
...

@end

In your cellForRowAtIndexPath add the following:

if([self.checkedIndexPath isEqual:indexPath])
{
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else 
{
    cell.accessoryType = UITableViewCellAccessoryNone;
}

How you code your tableView:didSelectRowAtIndexPath: will depend on the behavior you want. If there always must be a row checked, that is, that if the user clicks on an already checked row use the following:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Uncheck the previous checked row
    if(self.checkedIndexPath)
    {
        UITableViewCell* uncheckCell = [tableView
                     cellForRowAtIndexPath:self.checkedIndexPath];
        uncheckCell.accessoryType = UITableViewCellAccessoryNone;
    }
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    self.checkedIndexPath = indexPath;
}

If you want to allow the user to be able to uncheck the row by clicking on it again use this code:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Uncheck the previous checked row
    if(self.checkedIndexPath)
    {
        UITableViewCell* uncheckCell = [tableView
                    cellForRowAtIndexPath:self.checkedIndexPath];
        uncheckCell.accessoryType = UITableViewCellAccessoryNone;
    }
    if([self.checkedIndexPath isEqual:indexPath])
    {
        self.checkedIndexPath = nil;
    }
    else
    {
        UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        self.checkedIndexPath = indexPath;
    }
}