如何在单元格选择/取消选择时正确切换UITableViewCell的accesoryType?
我正在尝试在选择/取消选择表格单元格时切换accesoryType …行为应该是:点击 – >将accessoryType设置为UITableViewCellAccessoryCheckmark – >再次点击单元格 – >回滚到UITableViewCellAccessoryNone类型。 我的控制器中的实现如下:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; [cell setAccessoryType:UITableViewCellAccessoryCheckmark]; } - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; [cell setAccessoryType:UITableViewCellAccessoryNone]; }
…无论如何,一旦将样式配置为UITableViewCellAccessoryCheckmark,我就无法将其恢复为UITableViewCellAccessoryNone ! 我也试过打电话:
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
但是没有删除复选标记……我该怎么办?
编辑:实现没问题,问题是在自定义UITableViewCell子类…抱歉:P
如果这是你想要的,试试这个
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { cell.accessoryType = UITableViewCellAccessoryNone; } else { cell.accessoryType = UITableViewCellAccessoryCheckmark; } }
如果您只想将一行用作复选标记,请使用此选项
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; cell.accessoryType = (cell.accessoryType == UITableViewCellAccessoryCheckmark) ? UITableViewCellAccessoryNone : UITableViewCellAccessoryCheckmark; if (_lastSelectedIndexPath != nil) { UITableViewCell *lastSelectedCell = [tableView cellForRowAtIndexPath:_lastSelectedIndexPath]; lastSelectedCell.accessoryType = UITableViewCellAccessoryNone; } _lastSelectedIndexPath = indexPath; }
再次敲击细胞等同于细胞的选择而不是取消选择。
您需要在- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
方法中进行- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
以检查cell.accessoryType == UITableViewCellAccessoryCheckmark
。
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath { [theTableView deselectRowAtIndexPath:[theTableView indexPathForSelectedRow] animated:NO]; UITableViewCell *cell = [theTableView cellForRowAtIndexPath:newIndexPath]; if (cell.accessoryType == UITableViewCellAccessoryNone) { cell.accessoryType = UITableViewCellAccessoryCheckmark; // Reflect selection in data model } else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { cell.accessoryType = UITableViewCellAccessoryNone; // Reflect deselection in data model } }