2012-11-01 14 views

risposta

6

La classe UICollectionView ha metodi per aggiungere/rimuovere elementi. Per esempio, per inserire un elemento in qualche index (nella sezione 0), modificare il proprio modello di conseguenza e poi fare:

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

La vista farà il resto.

+0

Così, quando ho primo uso '[UICollectionView reloadData]' dovrei salvare l'indice dell'ultima cella utilizzata, e poi, quando chiamo il metodo per aggiungere più celle dovrei usare la sua ultima indexPath cellule, corretto ? @ chris –

+0

Non è necessario '[UICollectionView reloadData]' quando si aggiungono elementi. Basta fare "insertItemsAtIndexPaths:" e assicurarci che le successive chiamate all'origine dati "metodi' collectionView: numberOfItemsInSection: 'e' collectionView: cellForItemAtIndexPath: 'riflettano le tue modifiche. – chris

+0

L'ho fatto in un primo momento ha funzionato. Ma, quando le nuove celle saranno visualizzate sul display, ricevo il messaggio: 'Termina l'applicazione a causa dell'eccezione non rilevata 'NSRangeException', motivo: '- [__ NSCFArray objectAtIndex:]: index (36) oltre i limiti (36)' ' @ chris sai cosa ho fatto di sbagliato? –

5

Il modo più semplice per inserire nuove celle a UICollectionView senza dover ricaricare tutta la sua cella è in base alle performBatchUpdates, che può essere fatto facilmente seguendo la procedura che segue.

// 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

questo metodo scompare le celle precedenti, quindi carica nuovamente e scorre collectionView in alto. –

Problemi correlati