在实例变量中跟踪检查了哪一行。
当用户选择新行时,首先取消选中之前选中的行,
然后检查新行并更新实例变量。
这里有更多细节。首先添加一个属性来跟踪当前选中的行。如果这是NSIndexPath,这是最简单的。
@interface RootViewController : UITableViewController {
...
NSIndexPath* checkedIndexPath;
...
}
...
@property (nonatomic, retain) NSIndexPath* checkedIndexPath;
...
@end
在您的cellForRowAtIndexPath 中添加以下内容:
if([self.checkedIndexPath isEqual:indexPath])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
您如何编码tableView:didSelectRowAtIndexPath: 将取决于您想要的行为。
如果必须始终检查一行,也就是说,如果用户单击已检查的行,请使用以下内容:
- (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;
}
如果您想让用户能够通过再次单击该行来取消选中该行,请使用以下代码:
- (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;
}
}