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;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…