当我使用reloadData时,为什么indexPathsForSelectedRows失败?如何修复它?

时间:2014-10-28 17:18:46

标签: ios objective-c uitableview

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath方法中,我有以下代码部分:

     if ([tableView isEqual:cheeseTableView]) {

    cell = [tableView cellForRowAtIndexPath:indexPath];

    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {



        cell.accessoryType = UITableViewCellAccessoryNone;




    } else {


        cell.accessoryType = UITableViewCellAccessoryCheckmark;



    }

    NSLog(@"Called didSelecRowAtIndexPath: cheeseTableView");

    self.cheeseIndexPath = [self.cheeseTableView indexPathsForSelectedRows];

}

该表具有以下功能:cheeseTableView.allowsMultipleSelection = YES;

在方法结束时,我有以下一行:[tableView reloadData];

当我使用代码时,[self.cheeseIndexPath count]总是返回一个。但是当我删除reloadData方法时,我得到了正确的计数,但没有任何显示应该如此。如何让它正确显示并获得正确的计数?

3 个答案:

答案 0 :(得分:1)

如果您尝试根据选择打开/关闭复选标记,那么如果您使用单元格重用,则使用单元格本身不是一个好方法。您需要将on / off值存储在与数据具有相同行数的数组中,然后在didSelectRow中需要切换值。在cellForRow中,使用此数组来适当地设置复选标记。

答案 1 :(得分:0)

这里有一些问题可以指导您朝着正确的方向前进。

1)为什么需要重新加载tableView的数据? IMO,您所展示的代码中没有任何内容值得重新加载数据。

2)self.cheeseIndexPath数组应该包含什么?

如果你想保留已经检查过的所有单元格的indexPath,我会在选择代码中添加/删除indexPath:

NSTableViewCell *currentCell = [tableView cellAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        // remove the indexPath from the array
        [self.cheeseIndexPath removeObject:indexPath];
        // change anything of the cell that was just selected
        currentCell.backgroundColor = [UIColor newColor];
    } else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        // add the indexPath from the array
        [self.cheeseIndexPath addObject:indexPath];
        // change anything of the cell that was just selected
        currentCell.backgroundColor = [UIColor newColor];
    }

3)[tableView indexPathsForSelectedRows]不会在tableView中返回cell.accessoryType == UITableViewCellAccessoryCheckmark的所有单元格。

此外,值得一提的是,所有不可见的细胞都应被视为零(因为出列机制)。

希望这会有所帮助......


修改 在代码片段中,我添加了注释和代码来处理更改单元格的背景颜色(回答@SonOfSeuss注释,而不是OP)。

答案 2 :(得分:0)

试试这段代码。在我的例子中,它在didSelectRowAtIndexPath方法中工作。

NSMutableArray * checkedCells = [NSMutableArray alloc] init];

    for (UIView *view in tableView.subviews) {
            for (ProductAddonTableViewCell *cell in view.subviews) {
                if (cello.accessoryType == UITableViewCellAccessoryCheckmark)                {      
                    [checkedCells addObject:cell];
                }
            }
    }