3

I'm trying to select all UICollectionViewCells after a UIButton is tapped.

How do I do this?

Just Shadow
  • 10,860
  • 6
  • 57
  • 75
Sandeep Sachan
  • 373
  • 3
  • 15

4 Answers4

3

Updated for Swift 3

Just Shadow's Answer updated to Swift 3

  for i in 0..<assetCollectionView.numberOfSections {
    for j in 0..<assetCollectionView.numberOfItems(inSection: i) {
        assetCollectionView.selectItem(atIndexPath: IndexPath(row: j, section: i), animated: false, scrollPosition: .none)
    }
}
Indrajit Sinh Rayjada
  • 1,243
  • 1
  • 14
  • 24
2

You can select all cells in the first section through:

for (NSInteger row = 0; row < [self.collectionView numberOfItemsInSection:0]; row++) {
    [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionNone];
}

If you have more than 1 section, just use another nested for loop to loop through all the sections.

Gasper
  • 5,679
  • 1
  • 18
  • 21
2

Here's the solution:

for (NSInteger i = 0; i < [_assetCollectionView numberOfSections]; i++)
{
    for (NSInteger j = 0; j < [_assetCollectionView numberOfItemsInSection:i]; j++)
    {
        [_assetCollectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:j inSection:i] animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    }
}
Just Shadow
  • 10,860
  • 6
  • 57
  • 75
2

Updated to Swift 4

Updated Indrajit Sinh Rayjada's answer and put into an extension, as this is so general that it really should be an extension.

extension UICollectionView {
    func selectAll() {
        for section in 0..<self.numberOfSections {
            for item in 0..<self.numberOfItems(inSection: section) {
                self.selectItem(at: IndexPath(item: item, section: section), animated: false, scrollPosition: [])
            }
        }
    }
}
d4Rk
  • 6,622
  • 5
  • 46
  • 60