我想为UITableView中的单个选择实施清单。另外,我需要默认选择一个单元格。这是我在cellForRowAtIndexPath中的实现:

NSUInteger row = [indexPath row];
NSUInteger oldRow = [lastIndexPath row];
cell.accessoryType = (row == oldRow && lastIndexPath != nil) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;

if (indexPath.row == selectedRow ) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
 }
else {
    cell.accessoryType = UITableViewCellAccessoryNone;
 }


didSelectRowAtIndexPath具有以下代码:

if (!self.lastIndexPath) {
    self.lastIndexPath = indexPath;
}

if ([self.lastIndexPath row] != [indexPath row])
{
    UITableViewCell *newCell = [tableView cellForRowAtIndexPath: indexPath];
    newCell.accessoryType = UITableViewCellAccessoryCheckmark;

    UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:self.lastIndexPath];
    oldCell.accessoryType = UITableViewCellAccessoryNone;

    self.lastIndexPath = indexPath;
}
else {
    UITableViewCell *newCell = [tableView cellForRowAtIndexPath: indexPath];
    newCell.accessoryType = UITableViewCellAccessoryCheckmark;
}


使用此代码,我可以获得默认的选中标记,但是每当我选择另一行时
第一个保持选中状态,直到我不单击该单元格。因此,如果我想选择所需的结果,该怎么办?

`

最佳答案

我认为代码有点太复杂了。您只需要一个属性:

NSInteger _selectedRow;

最初定义时,它将提供默认的选定行。并且还将保留先前的选择(当寻找要“取消选择”的单元格时):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_IDENTIFIER];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL_IDENTIFIER];
    }

    if ([indexPath row] == _selectedRow) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }

    cell.textLabel.text = [NSString stringWithFormat:@"Row %d", indexPath.row];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_selectedRow >= 0) {
        [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_selectedRow inSection:0]].accessoryType = UITableViewCellAccessoryNone;
    }
    _selectedRow = [indexPath row];
    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


创建此视图时,如果您分配:

_selectedRow = 1;

然后将自动选择第二行。值-1表示没有默认选择,并且以上两种方法将自动添加/删除点击的行中的选中标记。

关于iphone - UITableView中的默认 list ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12412649/

10-11 14:49
查看更多