Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: reload single cell of UICollectionView

I am trying to follow the following post on reload a cell in a UICollectionView:

UICollectionView update a single cell

I know that I ultimately want something that looks like this:

[self.collectionView reloadItemsAtIndexPaths:??];

But I don't know how to find and pass the indexPath of a particular cell. Can anyone provide any pointers?

I have an NSMutableArray that contains all the cell information (imageViews that are generated in each cell). Ideally, what I'd like to do is pass the index of the NSMutableArray to refresh the corresponding cell on the page. But I'm not sure how the numerical index gets translated into an indexPath.

Thanks in advance for your help!

like image 949
scientiffic Avatar asked Sep 07 '14 06:09

scientiffic


4 Answers

It depends on your implementation and how you have grouped your cells into sections but let's assume you have one section and each element in your array corresponds to a row in your table.

If you wanted to reload a cell corresponding to an array element at index x all you need to do is write

[_collectionView performBatchUpdates:^{
    [_collectionView reloadItemsAtIndexPaths:@[[NSIndexPath x inSection:0]]];
} completion:^(BOOL finished) {}];

Conversely, if you have the cell but want to find its index path you can always call [collectionView indexPathForCell:myCell]

like image 109
Daniel Galasko Avatar answered Nov 20 '22 01:11

Daniel Galasko


Toy have to pass an array containing the indexPaths that you want to be reloaded.

[self.collectionView reloadItemsAtIndexPaths: indexpathArray];

NSIndexPath has some property names section and row, both represents a cell. If your collection view has single section, you can create a NSIndexPath by setting its section = 0;

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rowIndex inSection:0];

Here rowIndex is your array index. Btw you have to make an array with you newly created indexpaths, then pass it to reloadItemsAtIndexPaths.

Hope this helps.. :)

like image 31
Rashad Avatar answered Nov 19 '22 23:11

Rashad


Obj-C

NSMutableArray *indexPaths = [[NSMutableArray alloc] init]    
[indexPaths addObject:indexPath];
[self.collectionView reloadItemsAtIndexPaths: indexPaths];

Swift 4.0

var indexPaths = [IndexPath]()
indexPaths.append(indexPath) 

if let collectionView = collectionView {
    collectionView.reloadItemsAtIndexPaths(indexPaths)
}
like image 34
Ashish Avatar answered Nov 19 '22 23:11

Ashish


You can use this way for Swift 5.1:

collectionViewOutletName.reloadItems(at: [IndexPath(row: indexNumber, section: sectionNumber)] )
like image 1
Sohanur Rahman Avatar answered Nov 19 '22 23:11

Sohanur Rahman