簡體   English   中英

在UICollectionView中的當前索引之前添加一個對象

[英]Adding an object before the current index in UICollectionView

我有一個簡單的集合視圖,其中包含兩種類型的單元格。 計數器單元格和“添加”單元格。 我的目標是在添加新對象之后將“添加”單元格保留在索引的末尾。 當我運行應用程序時,出現“添加”單元格,但是當按下“添加”按鈕時出現錯誤。

這是錯誤:

由於未捕獲的異常“ NSInternalInconsistencyException”而終止應用程序,原因:“無效更新:第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]]];

}

感謝任何可以幫助您的人!

該錯誤指示更改數據源時出現數據源問題。 可變字典中的鍵數不正確。

大概您將NSIndexPath用作鍵,將所需的數據用作值。 我認為使用數組更容易(然后indexPath.row將以正確的順序簡單地指向正確的對象)。

檢查您在數據源中更改數據的更新方法。 您應該確保字典中包含預期的項目數。

在您的錯誤消息中,插入前后的1項似乎表明您的字典可能變為nil ,因此返回零計數。 確保您具有正確實例化的實例變量。

在對象數組中,每當添加新對象時,都要為新對象創建新數組,然后像這樣添加它

 [existingArray addObjectsFromArray:newarray];

順序將保持

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM