有趣的循环行为?

时间:2013-10-25 05:55:26

标签: ios objective-c cocoa-touch uitableview

我有一个tableview控制器,我希望能够选择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次,然后停止允许我检查。我错过了什么吗?感谢。

1 个答案:

答案 0 :(得分:2)

您始终检查for循环内的相同单元格( indexPath 是您当前选择的单元格): if([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark)

相关问题