-2

一度に2つのセルしか選択できないテーブルビューコントローラーがあります。既に 2 つのセルがチェックされている場合、別のチェックされていないセルをタップすると、最初のセルのチェックが外れ、最新の 2 つのセルがチェックされます。これが私がうまく使っていないものです:

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

         int count = 0;
    int i = 0;

    NSIndexPath *datPath = 0;
    for (UITableViewCell *cell in [self.tableView visibleCells]) {
        i++;
        datPath = [NSIndexPath indexPathForRow:i inSection:0];
        if([tableView cellForRowAtIndexPath:datPath].accessoryType == UITableViewCellAccessoryCheckmark){
        count++;
        }
    }

    if(count == 0){
        firstChecked = indexPath;
        [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

    if(count == 1){
        secondChecked = indexPath;
        [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

    if(count == 2){
        [tableView cellForRowAtIndexPath:firstChecked].accessoryType = UITableViewCellAccessoryCheckmark;
        firstChecked = secondChecked;
        secondChecked = indexPath;
        [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

    NSLog(@"Count is equal to: %d",count);

疑問に思っている人のために、私のテーブル ビューでは複数選択が許可されています。上記のコードで何が起こるかは次のとおりです。カウントは値がオフになっているため、3回チェックでき、その後停止してまったくチェックできなくなります。何か不足していますか?ありがとう。

4

1 に答える 1

2

for ループ内で常に同じセルをチェックします ( indexPathは現在選択しているセルです)。 if([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark)

于 2013-10-25T06:03:29.937 に答える