如何在单元格选择/取消选择时正确切换UITableViewCell的accesoryType?

时间:2012-01-15 14:46:20

标签: ios uitableview

我正在尝试在选择/取消选择表格单元格时切换 accesoryType ...行为应为:tap - >将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

4 个答案:

答案 0 :(得分:13)

如果这是你想要的话,试试这个

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    {   
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        else
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }

答案 1 :(得分:2)

如果您想只使用一行作为复选标记,请使用此

- (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;
} 

答案 2 :(得分:0)

再次点击单元格等同于选择单元格而不是取消选择。

您需要在- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath方法中进行切换,以检查cell.accessoryType == UITableViewCellAccessoryCheckmark

答案 3 :(得分:0)

- (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
    }
}
相关问题