UITableView中的附件视图:视图不会更新

时间:2010-05-22 02:13:14

标签: iphone uitableview

当用户在表视图中选择行时,我正在尝试向项添加复选标记。但是,视图未刷新且复选标记不显示:

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell* oldCell = [self tableView:tv cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0]];
    oldCell.accessoryType = UITableViewCellAccessoryNone;

    if (indexPath.section == 0) {
        selectedIndex = indexPath.row;
    }

    UITableViewCell* newCell = [self tableView:tv cellForRowAtIndexPath:indexPath];
    newCell.accessoryType = UITableViewCellAccessoryCheckmark;

    [tv deselectRowAtIndexPath:indexPath animated:NO];
}

这可能是什么原因?

1 个答案:

答案 0 :(得分:6)

直接在tv对象上调用cellForRowAtIndexPath而不是通过self来确保获得正确的单元格引用:

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *oldCell = [tv cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0]];
    oldCell.accessoryType = UITableViewCellAccessoryNone;

    if (indexPath.section == 0) {
        selectedIndex = indexPath.row;
    }

    UITableViewCell *newCell = [tv cellForRowAtIndexPath:indexPath];
    newCell.accessoryType = UITableViewCellAccessoryCheckmark;

    [tv deselectRowAtIndexPath:indexPath animated:NO];
}

还要确保在cellForRowAtIndexPath中有这样的逻辑:

...
if (indexPath.row == selectedIndex)
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
    cell.accessoryType = UITableViewCellAccessoryNone;
...
return cell;

否则,在滚动屏幕后,单元格将保留在单元格上,即使您选择了另一个单元格,也会返回到屏幕上。