【问题标题】:Adding an object before the current index in UICollectionView在 UICollectionView 中的当前索引之前添加一个对象
【发布时间】:2013-12-05 23:03:27
【问题描述】:

我有一个简单的集合视图,它有两种类型的单元格。一个计数器单元和一个“添加”单元。我的目标是在添加新对象后让“添加”单元格保留在索引的末尾。当我运行应用程序时,会出现我的“添加”单元格,但按下“添加”按钮时出现错误。

这是错误:

由于未捕获的异常而终止应用程序 'NSInternalInconsistencyException',原因:'无效更新:无效 第 0 节中的项目数。包含在第 0 节中的项目数 更新后的现有节(1)必须等于 更新前该部分中包含的项目 (1),加号或减号 从该部分插入或删除的项目数(插入 1 个, 0 已删除)加上或减去移入或移出的项目数 该部分(0 移入,0 移出)。'

这是我的代码:

// retrievedCounters is an NSMutableDictionary

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
   // only want one section
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    // get the current count and add one for the "add" cell
    return retrievedCounters.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell;

    // check whether the index path is at the very end and add the appropriate cell

    if (indexPath.row == retrievedCounters.count) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddCounter" forIndexPath:indexPath];
    }

    else {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CounterCell" forIndexPath:indexPath];
    }

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];

     // insert new counter at index path
     [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:retrievedCounters.count-1 inSection:0]]];

}

感谢任何可以提供帮助的人!

【问题讨论】:

    标签: ios objective-c uicollectionview


    【解决方案1】:

    该错误表明更改数据源时出现数据源问题。可变字典中的键数不正确。

    大概您使用NSIndexPaths 作为键和您需要的数据作为值。我认为使用数组更容易(indexPath.row 会简单地以正确的顺序指向正确的对象)。

    检查您更改数据源中数据的更新方法。您应该确保您的字典包含预期数量的项目。

    在您的错误消息中,插入前后的 1 项似乎表明您的字典可能变为 nil,因此返回零计数。确保您有一个正确实例化的实例变量。

    【讨论】:

    • 你是对的,我的数据源没有被正确更改。有时用一双新的眼睛看你的代码真是太好了。谢谢。
    【解决方案2】:

    每当您添加新对象时,都在您的对象数组中 为新对象创建新数组,然后像这样添加它

     [existingArray addObjectsFromArray:newarray];
    

    将保持顺序

    【讨论】:

    • 他使用的不是对象数组,而是字典。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2021-06-16
    • 2016-05-08
    • 2013-09-10
    • 2012-11-24
    • 2018-04-10
    相关资源
    最近更新 更多