I am in the middle of creating an application where I have a button on a tool bar which selects all the items inside a collection view.
But the problem that I am facing is, when I tap on the button it selects only those items that are visible on the screen. This is due to the CELL REUSE functionality.
Is there any way that I can select all the cells, even those which are not currently visible to the user?
Thanks J
Updated for Swift 3
updated Gasper Kolenc answer to swift 3 , for future use if anyone looking for this in swift 3 then..
Swift 3 solution:
I've created a simple extension on
UICollectionView
for selecting and deselecting:It is not possible to have all cells selected when using cell reuse.
Due to cell reuse the number of actual cells which exist at any moment is a couple more than the number of cells currently visible. i.e. 6 cells visible is about 8 cells existing.
You are able to find out how many visible cells there are with
The solution is to have the
selected
value stored within the UICollectionView datasource and use that value for when you customise a cell insidecellForItemAtIndexPath
This is possible even with cell reuse. You can select all cells in the first section through:
If you have more than 1 section, just use another nested for loop to loop through all the sections.
I struggled thro the same problem where I wanted to display photos and allow the user to select multiple photos, with select-all and deselct-all options. It turned out that [self.collectionView selectItemAtIndexPath:] does not work for selecting all cells.
So I ended up in maintaining a separate state flag along with the data source. In my case, each cell displayed a photo, so I had to maintain a separate BOOL array, where each element represents the current selection state of the corresponding photo in the data source array.
Please see the code below: (Source: http://heliumapps.weebly.com/blog/uicollectionview-and-cell-selection)