35

I have allowMultipleSelection enabled in a collection view. The cells change to and from their selected states when tapped. All good. However, when I want to reset the entire view to selected state:NO using the code below, the cells appears to be entirely deselected until I then make a new selection, at which point all previously selected cells show their previously selected state.

i.e. despite appearances the collectionview is not updating it's current selection list when I programmatically deselect the cells

- (void)clearCellSelections {
   for (LetterCell  *cell in self.collectionView.visibleCells) {
        [cell prepareForReuse];
    }
}

In custom cell:

- (void)prepareForReuse
{
    [super prepareForReuse];
    [self setSelected:NO];
}

What am I doing wrong? Is there another way to deselect all cells?

Thanks TBlue for taking a look

1
  • 1
    Refresh the collectionview control?
    – El Tomato
    Commented Jan 22, 2013 at 14:04

9 Answers 9

86

You can iterate over - [UICollectionView indexPathsForSelectedItems]:

for (NSIndexPath *indexPath in [self.collectionView indexPathsForSelectedItems]) {
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}
5
  • 3
    Small correction. There is an animated parameter. Thus it should be: [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
    – bert
    Commented Apr 11, 2014 at 12:28
  • Edited for animated parameter.
    – qorkfiend
    Commented May 22, 2014 at 20:21
  • 1
    You also need self.collectionView.reloadData()
    – Ace Green
    Commented Jun 5, 2015 at 22:24
  • Without reloadData() only the visible cells will be updated. Commented Jan 12, 2017 at 13:31
  • @Scooter Can you show me the way? I didn't get any effect.
    – AnLT
    Commented Jun 25, 2017 at 17:24
22

The simplest way to deselect all selected cells in a UICollectionView is simply to pass nil as the first argument to collectionView.selectItem(at:, animated:, scrollPosition:). E.g.,

collectionView.selectItem(at: nil, animated: true, scrollPosition: [])

will clear the current selection state, even when allowsMultipleSelection == true.

2
  • This is a much better, more concise answer. I think however you still need to iterate over cells if you want to deselect all cells in a section (and leave the other sections untouched). Commented Feb 15, 2016 at 23:07
  • Short and simple answer
    – Jay Patel
    Commented Nov 17, 2017 at 6:58
11

You could say that UITableViewCell.selected only sets the 'visible state/appearance' of the cell and it's contents. You could deselect the cells, by iterating over all indexPaths of the tableView and call deselectRowAtIndexPath:animated: for each one.

For instance:

for (int i=0; i < self.myData.count; i++) {
    [self.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES];
}

EDIT: I totally agree with @BenLings and @JeremyWiebe's comments, that @qorkfiend's solution is preferred over this one.

3
  • @ fguchelaar how to make it work in UICollectionView. It is not working there. I tried this way [self.collectionView didDeselectItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]]; Commented May 22, 2013 at 10:58
  • 3
    @qorkfiend's answer is preferable to this one
    – Ben Lings
    Commented Feb 4, 2014 at 15:12
  • 1
    Agree with @BenLings especially when your data set is large. With this solution you have to enumerate every single item, which gets worse if you are using an NSFetchedResultsController with Core Data. Commented Sep 30, 2014 at 19:23
4

Just in case this is simple solution in Swift:

extension UICollectionView {
    func deselectAllItems(animated animated: Bool = false) {
        for indexPath in self.indexPathsForSelectedItems() ?? [] {
            self.deselectItemAtIndexPath(indexPath, animated: animated)
        }
    }
}
2

For swift 3 Extension would looks like this:

import UIKit

extension UICollectionView {
    func deselectAllItems(animated: Bool = false) {
        for indexPath in self.indexPathsForSelectedItems ?? [] {
            self.deselectItem(at: indexPath, animated: animated)
        }
    }
}
1

This is complete if you want to delegate also be called

for (NSIndexPath *indexPath in [self.cuisineCollection indexPathsForSelectedItems]) {
            [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
            [collectionView.delegate collectionView:cuisineCollection didDeselectItemAtIndexPath:indexPath];
        }
0

I created a global variable called toggleCellSelection, then ran this in the didSelectItemAt function:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("select cell \(indexPath.row)")

    let cell = collectionView.cellForItem(at: indexPath)
    if (toggleCellSelection == true) {
        toggleCellSelection = false
        cell?.layer.borderWidth = 0
        cell?.layer.borderColor = UIColor.clear().cgColor
    } else {
        toggleCellSelection = true
        cell?.layer.borderWidth = 5
        cell?.layer.borderColor = #colorLiteral(red: 0.8779790998, green: 0.3812967837, blue: 0.5770481825, alpha: 1).cgColor
    }


}
0

Not that this answer is the necessarily 'the best', but since no one mentioned it, I'll add it.

You can simply call the following.

collectionView.allowsSelection = false
collectionView.allowsSelection = true
0

This is @qorkfiend answer in Swift

// this is an array of the selected item(s) indexPaths
guard let indexPaths = collectionView.indexPathsForSelectedItems else { return }

// loop through the array and individually deselect each item
for indexPath in indexPaths{
    collectionView.deselectItem(at: indexPath, animated: true)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.