带复选标记的UITableViewCell,复制复选标记

到目前为止search堆栈溢出我还没有find像我的情况。 任何帮助都非常感谢:我一直看到,如果我在A人身上勾了一个勾,H人也会有一个人,同样也会有一个10人左右的人。 基本上每10个重复一个复选标记。

这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {static NSString *CellIdentifier = @"MyCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", [[myArrayOfAddressBooks objectAtIndex:indexPath.row] objectForKey:@"FirstName"],[[myArrayOfAddressBooks objectAtIndex:indexPath.row] objectForKey:@"LastName"]]; cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [[myArrayOfAddressBooks objectAtIndex:indexPath.row] objectForKey:@"Address"]]; return cell; 

}

在我做了索引pathselect行我有这样的:

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell; cell = [self.tableView cellForRowAtIndexPath: indexPath]; if ([[myArrayOfAddressBooks objectAtIndex:indexPath.row] objectForKey:@"emailSelected"] != @"YES") { cell.accessoryType = UITableViewCellAccessoryCheckmark; [[myArrayOfAddressBooks objectAtIndex:indexPath.row] setValue:@"YES" forKey:@"emailSelected"]; } else { cell.accessoryType = UITableViewCellAccessoryNone; [[myArrayOfAddressBooks objectAtIndex:indexPath.row] setValue:@"NO" forKey:@"emailSelected"]; } 

这是由于如何UITableView “回收” UITableViewCell效率的目的,以及如何标记你的单元格时,他们被选中。

您需要刷新/设置您在tableView:cellForRowAtIndexPath:处理/创build的每个单元格的accessoryTypetableView:cellForRowAtIndexPath: 您正确更新myArrayOfAddressBooks数据结构中的状态,并且只需要在tableView:cellForRowAtIndexPath:使用此信息tableView:cellForRowAtIndexPath:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"MyCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } NSDictionary *info = [myArrayOfAddressBooks objectAtIndex:indexPath.row]; cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", [info objectForKey:@"FirstName"],[info objectForKey:@"LastName"]]; cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [info objectForKey:@"Address"]]; cell.accessoryType = ([[info objectForKey:@"emailSelected"] isEqualString:@"YES"]) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone; return cell; } 

另外,除非有充分理由将状态保存为@"Yes"@"No"string,为什么不把它们保存为[NSNumber numberWithBool:YES][NSNumber numberWithBool:NO] ? 这将简化你的逻辑,当你想要做比较而不必使用isEqualToString:所有的时间。

例如

  cell.accessoryType = ([[info objectForKey:@"emailSelected"] boolValue]) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;