UICollectionView how to deselect all

Not all of the selected cells may be on screen at the point when you are clearing the selection status, so collectionView.cellForItemAtIndexPath(indexPath) may return nil. Since you have a force downcast you will get an exception in this case.

You need to modify your code to handle the potential nil condition but you can also make your code more efficient by using the indexPathsForSelectedItems property of UICollectionView

 let selectedItems = followCollectionView.indexPathsForSelectedItems
 for (indexPath in selectedItems) {
     followCollectionView.deselectItemAtIndexPath(indexPath, animated:true)
     if let cell = followCollectionView.cellForItemAtIndexPath(indexPath) as? FollowCell {
        cell.checkImg.hidden = true
     }
 }

To simplify further, you could just do

followCollectionView.allowsSelection = false
followCollectionView.allowsSelection = true

This will in fact correctly clear your followCollectionView.indexPathsForSelectedItems even though it feels very wrong.


Using Extension in Swift 4

extension UICollectionView {

    func deselectAllItems(animated: Bool) {
        guard let selectedItems = indexPathsForSelectedItems else { return }
        for indexPath in selectedItems { deselectItem(at: indexPath, animated: animated) }
    }
}

collectionView.indexPathsForSelectedItems?
    .forEach { collectionView.deselectItem(at: $0, animated: false) }