用于UITableViewCellAccessoryCheckmark的逻辑

我想做一个典型的情况:当用户select任何单元格时,它的附件types会打勾。 只有一个单元的附件types可以勾选。 然后我想保存在NSUserDefaults的indexPath.row所以我的应用程序将能够知道哪些单元格用户select,并作出一些select的变化。 所以我写了这个错误的代码:

didSelectRowAtIndexPath方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // checkedIndexPath is NSIndexPath if(self.checkedIndexPath) { UITableViewCell* uncheckCell = [tableView cellForRowAtIndexPath:self.checkedIndexPath]; uncheckCell.accessoryType = UITableViewCellAccessoryNone; } UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath]; cell.accessoryType = UITableViewCellAccessoryCheckmark; self.checkedIndexPath = indexPath; [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithInt:self.checkedIndexPath.row]forKey:@"indexpathrow" ]; } 

的cellForRowAtIndexPath

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Part of code from cellForRowAtIndexPath if(indexPath.row == [[[NSUserDefaults standardUserDefaults]objectForKey:@"indexpathrow"]intValue ]) { cell.accessoryType = UITableViewCellAccessoryCheckmark; } else { cell.accessoryType = UITableViewCellAccessoryNone; } return cell; } 

但是,这个代码工作不好。 当你打开UITableView ,表格中已经有一个已经选好的单元格,当你按下另一个单元格的时候,有两个复选checkmarked单元格…我怎样才能改善我的代码,或者我应该改变它的整个? 有什么build议么 ? 谢谢 !

试试这个代码:

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // checkedIndexPath is NSIndexPath NSIndexPath *previousSelection = self.checkedIndexPath; NSArray *array = nil; if (nil != previousSelection) { array = [NSArray arrayWithObjects:previousSelection, indexPath, nil]; } else { array = [NSArray arrayWithObject:indexPath]; } self.checkedIndexPath = indexPath; [tableView reloadRowsAtIndexPaths:array withRowAnimation: UITableViewRowAnimationNone]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Part of code from cellForRowAtIndexPath NSString *cellID = @"CellID"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; if (nil == cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID]; [cell autorelease]; } // some code for initializing cell content cell.selectionStyle = UITableViewCellSelectionStyleNone; if(self.checkedIndexPath != nil && indexPath.row == self.checkedIndexPath.row) { cell.accessoryType = UITableViewCellAccessoryCheckmark; } else { cell.accessoryType = UITableViewCellAccessoryNone; } return cell; }