2012-11-01 10 views
9

すでに一部のセルでいっぱいになっている既存のUICollectionViewにさらにいくつかのセルを追加しようとしています。既存のUICollectionViewにさらにUICollectionViewCellを追加します。

私はCollectionView reloadDataを使用しようとしましたが、コレクションビュー全体を再読み込みしているようで、セルを追加したかっただけです。

誰でも私を助けることができますか?

答えて

6

UICollectionViewクラスにはアイテムを追加/削除するメソッドがあります。例えば、いくつかのindexに項目を挿入する(セクション0に)、それに応じてモデルを変更して行います。

int indexPath = [NSIndexPath indexPathForItem:index]; 
NSArray *indexPaths = [NSArray arrayWithObject:indexPath inSection:0]; 
[collectionView insertItemsAtIndexPaths:indexPaths]; 

ビューは残りを行います。

+0

、 ? @chris –

+0

アイテムを追加するときに '[UICollectionView reloadData]'はまったく必要ありません。 'insertItemsAtIndexPaths:'を実行して、データソースのメソッド 'collection':numberOfItemsInSection:'と 'collectionView:cellForItemAtIndexPath:'へのその後の呼び出しで変更が反映されるようにしてください。 – chris

+0

私はそれが最初に働いた。しかし、新しいセルがディスプレイに表示されるとき、私はメッセージを受け取ります: 'キャッチされていない例外によりアプリケーションを終了しています 'NSRangeException'、理由: ' - [__ NSCFArrray objectAtIndex:]:インデックス(36) ' @chrisあなたは私が間違っていたことを知っていますか? –

5

すべてのセルを再ロードすることなくUICollectionViewに新しいセルを挿入する最も簡単な方法は、以下の手順で容易に行うことができるperformBatchUpdatesを使用することです。私は最初の `[UICollectionView reloadData]`私が使用した最後のセルのインデックスを保存する必要があり、その後、私はより多くのセルを追加するメソッドを呼び出したとき、私はその最新のセルindexPathを使用する必要があり、正しい使用ので

// Lets assume you have some data coming from a NSURLConnection 
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *erro) 
{ 
     // Parse the data to Json 
     NSMutableArray *newJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 

     // Variable used to say at which position you want to add the cells 
     int index; 

     // If you want to start adding before the previous content, like new Tweets on twitter 
     index = 0; 

     // If you want to start adding after the previous content, like reading older tweets on twitter 
     index = self.json.count; 

     // Create the indexes with a loop 
     NSMutableArray *indexes = [NSMutableArray array]; 

     for (int i = index; i < json.count; i++) 
     { 
      [indexes addObject:[NSIndexPath indexPathForItem:i inSection:0]]; 
     } 

     // Perform the updates 
     [self.collectionView performBatchUpdates:^{ 

      //Insert the new data to your current data 
      [self.json addObjectsFromArray:newJson]; 

      //Inser the new cells 
      [self.collectionView insertItemsAtIndexPaths:indexes]; 

     } completion:nil]; 
} 
+0

このメソッドは以前のセルを消してから再び読み込み、collectionViewを上にスクロールします。 –

関連する問題