【问题标题】:iOS index 2 beyond bounds error while inserting rows插入行时iOS索引2超出范围错误
【发布时间】:2013-07-28 16:03:42
【问题描述】:

我有一个静态的 UITableView,它是通过故事板配置的。我正在尝试使用 insertRowsAtIndexPaths:withRowAnimation: 在 didSelectRowAtIndexPath 期间插入一些行,但出现错误:

* 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[__NSArrayI objectAtIndex:]:索引 2 超出范围 [0 .. 1]'。

我已经实现了 numberOfRowsInSection,但每次仍然出现此错误。它是否与表是静态的而不是动态的有关?谢谢。

if (indexPath.section == 1) {
    if (indexPath.row == 1) { // Map Type Cell

        self.isSelectingMapType = YES;

        NSArray *indexPaths = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:2 inSection:1], [NSIndexPath indexPathForRow:3 inSection:1], [NSIndexPath indexPathForRow:4 inSection:1], [NSIndexPath indexPathForRow:5 inSection:1], nil];
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
        //[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        if (self.isSelectingMapType == YES) {
            return 6;
        }
        return 2;
    }
    return 0;
}

【问题讨论】:

    标签: ios uitableview insert tableview


    【解决方案1】:

    您可能想快速查看Apple's Table View Programming Guide,了解表视图在更新块中的行为方式。

    动画块中的删除和重新加载操作指定应该删除或重新加载原始表中的哪些行和部分;插入指定应将哪些行和部分添加到结果表中。用于标识节和行的索引路径遵循此模型。

    您不能使用这些索引路径,因为它们还没有出现在表中。 由于您在-tableView:numberOfRowsInSection: 中检查了isSelectingMapType,您应该能够简单地要求重新加载表格视图以达到您想要的结果。

    【讨论】:

    • 这是有道理的。我知道我可以通过调用 reloadData 来实现它,但是有没有像使用 insertRows 一样实现动画效果?
    • 使用 -reloadSections:withRowAnimation 就像你在你的 sn-p 中一样就足够了。我粘在一起的一个小原型就很好地使用了它。那么就不需要为各个行设置动画了。
    • 好的,谢谢。我得到了它的工作!另一件事是,当触发重新加载时,原来的 2 个单元格消失了,下面出现了 4 个新单元格。有什么原因吗?
    【解决方案2】:

    我的所有应用程序都使用情节提要,但从未尝试使用静态单元格将行插入 UITableView。我所做的是创建情节提要中需要的所有行,并以编程方式隐藏/显示它们,而不是插入它们。

    首先,在情节提要中创建您想要的所有单元格。然后,修改代码如下:

    if (indexPath.section == 1) 
    {
        if (indexPath.row == 1) 
        { 
            self.isSelectingMapType = YES;
            [self.tableView reloadData];
        }
    }
    

    【讨论】:

    • 是的,我知道我能做到。我只是喜欢动画。无论如何要为其添加动画?
    猜你喜欢
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多