【问题标题】:Funny for loop behavior? [closed]有趣的 for 循环行为? [关闭]
【发布时间】:2013-10-25 05:55:25
【问题描述】:

我有一个表格视图控制器,我希望能够在其中选择 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 次,然后完全停止允许我检查。我错过了什么吗?谢谢。

【问题讨论】:

  • 当您已经选择了两个时,您并没有取消设置配件类型;你又设置了[tableView cellForRowAtIndexPath:firstChecked].accessoryType = UITableViewCellAccessoryCheckmark;

标签: ios objective-c cocoa-touch uitableview


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 2013-01-06
    • 2020-09-17
    • 1970-01-01
    相关资源
    最近更新 更多