代码之家  ›  专栏  ›  技术社区  ›  Brandon Schlenker

UITableView insertRowsAtIndexPaths无序

  •  1
  • Brandon Schlenker  · 技术社区  · 14 年前

    我目前有一个UISegmentedControl设置,可以在其值更改时添加/删除表视图单元格。移除单元格效果很好,但是当我插入单元格时,它们每隔一段时间的顺序是相反的。

    NSArray *addindexes = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:2 inSection:0], [NSIndexPath indexPathForRow:3 inSection:0], [NSIndexPath indexPathForRow:4 inSection:0], nil];
    NSArray *removeindexes = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:2 inSection:0], [NSIndexPath indexPathForRow:3 inSection:0], [NSIndexPath indexPathForRow:4 inSection:0], nil];
    [self.tableView beginUpdates];
    
    switch (switchType.selectedSegmentIndex) {
        case 0:
            [self.tableView insertRowsAtIndexPaths:addindexes withRowAnimation:UITableViewRowAnimationTop];
            break;
        case 1:
            [self.tableView deleteRowsAtIndexPaths:removeindexes withRowAnimation:UITableViewRowAnimationTop];
    
            break;
        default:
            break;
    }
    
    [self.tableView endUpdates];}
    

    例如,每次我添加/删除单元格时,它们的顺序都是相反的(4,3,2代替2,3,4)
    1) 删除单元格-添加单元格-正确顺序

    3) 删除单元格-添加单元格-正确顺序

    4 回复  |  直到 14 年前
        1
  •  1
  •   drawnonward    14 年前

    您的代码示例只显示索引。单元格的显示顺序由您的 tableView:cellForRowAtIndexPath: 方法。

        2
  •  0
  •   Brandon Schlenker    14 年前

    每个单元格创建一个UITextField。为了防止它被多次绘制,我使用了

    if (!someTextField)
    

    [someTextField removeFromSuperview] 因为行正在被删除。

        3
  •  0
  •   Community kfsone    4 年前

    第0节

    • 第0行/切换标记为0(永久主开关,插入/删除第1-3节)

    第1节

    • 第0行/切换标记为
    • 第1行/切换标记为

    第2节

    • 第0行/切换标记为 3.
    • 第1行/切换标记为 4.

    第3节

    • 5.

    在关闭主切换以删除第1-3节,然后再打开以插入第1-3节之后,切换标记的顺序相反:

    第0节

    • 第0行/切换标记为0(永久主开关,插入/删除第1-3节)

    第1节

    • 第0行/切换标记为
    • 第1行/切换标记为 4.

    第2节

    • 第0行/切换标记为 3.
    • 2.

    第3节

    • 1.

    我的工作方式就是放弃 toggle.tag = myRowIteratorVariable 内部 if( cell == nil ) 阻止。相反,在该块之后,我将toggle.tag设置为在数据中预定义的行ID:

    - (UITableViewCell *)tableView:(UITableView *)tableView 
        cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UISwitch *toggle = nil;
        ...
        if( cell == nil )
        {
            ...
            toggle = [[UISwitch alloc] init];
            //toggle.tag = myRowIteratorVariable;
            ...
        }
    
        NSDictionary *section = [myTableViewSectionArray objectAtIndex:indexPath.section];
        NSArray *rowIds = [section objectForKey:@"rowIds"];
        int rowId = [[rowIds objectAtIndex:indexPath.row] intValue];
        toggle.tag = rowId;
    
        return cell;
    }
    
        4
  •  0
  •   inix    9 年前