2015-07-21 84 views
1

我試圖將新單元格添加到我的集合視圖中,僅當它已包含多個項目時纔會添加。我沒有太多的收集意見,並在文檔和本網站的研究還沒有幫助解決這個問題呢。所以,在我的cellForItemAtIndexPath方法,我做了檢查,看看它是否填充。如果沒有,我增加該小區,像這樣:將新單元格插入到UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    if (self.myArray.count != 0) { 
     return self.myArray.count + 1; 
    } 
    else { 
     return self.myArray.count; 
    } 
} 

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 

    MyNormalCollectionViewCellS *cells = (MyNormalCollectionViewCells *) [collectionView dequeueReusableCellWithReuseIdentifier:@"MyNormalCollectionViewCells」 forIndexPath:indexPath]; 
    cell.clipsToBounds = NO; 
    DataClass *data = [self.myArray objectAtIndex:indexPath.row]; 
    [cells configureMyNormalCellsWith:data]; 

    if (0 < self.myArray.count) { 

     UICollectionViewCell *deleteCell = [UICollectionViewCell new]; 
     deleteCell.backgroundColor = [UIColor yellowColor]; 
     NSArray *newData = [[NSArray alloc] initWithObjects:deleteCell, nil]; 

     [self.myArray addObjectsFromArray:newData]; 

     NSMutableArray *arrayWithIndexPaths = [NSMutableArray array]; 
     [self.myCollectionView insertItemsAtIndexPaths:arrayWithIndexPaths]; 

     return deleteCell; 
    } 

    return cell; 

} 

出於某種原因,我有一個斷言被拋出,他說:

***終止應用程序由於未捕獲的異常「NSInternalInconsistencyException」,原因:'無效更新:無效 部分0中的項目數。更新(7)後, 現有部分中包含的項目數量必須等於更新前(6)部分中包含的 項目數量 ,加號或減號 從該部分插入或刪除的項目數(0 0刪除)並加上或減去移入或移出 該項(0移入,0移出)的項目數。

當然,這個數字通常是變化的,但它總是對這個額外的細胞感到憤怒。一切都很好,直到我嘗試並添加它。現在,對收集視圖不熟悉,並在瀏覽本網站上的相關問題後,我決定是時候向專業人士提問。

有誰知道我應該如何改變這段代碼才能完成我想要做的事情?

回答

2

請勿修改collectionView:cellForItemAtIndexPath:中的數據源。返回不同數量的項目在- collectionView:numberOfItemsInSection:代替:

- (NSInteger)collectionView:(UICollectionView *)collectionView 
    numberOfItemsInSection:(NSInteger)section { 
    if (self.dataArray.count > 0) { 
     return self.dataArray.count + 1; 
    } 
    else { 
     return 0; 
    } 
} 

collectionView:cellForItemAtIndexPath:您應該返回你的「正常」細胞的「正常」項目,「額外的」細胞用於額外的一個,這取決於indexPath.row值。例如:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (indexPath.row < self.dataArray.count) { // if indexPath.row is within data array bounds 
     // dequeue, setup and return "normal" cell 
    } else { // this is your "+1" cell 
     // dequeue, setup and return "extra" cell 
    } 
} 
+0

謝謝。我試過這個解決方案,但我碰到錯誤'NSRangeException',原因:*** - [__ NSArrayM objectAtIndex:]:索引6超越界限[0..5]' – John

+0

你想'self.dataArray [ 'indexPath.row]'在'(indexPath.row Kreiri

+0

或者我如何更改我的代碼以實現此目的?認爲我正確理解了你,但不能有... – John