UICollectionView how to deselect all

后端 未结 6 2187
被撕碎了的回忆
被撕碎了的回忆 2021-02-12 23:26

I have a FollowVC and FollowCell Setup with collection View. I can display all the datas correctly into my uIcollection view cell using the following code with no problem.

相关标签:
6条回答
  • 2021-02-12 23:34

    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.

    0 讨论(0)
  • 2021-02-12 23:36

    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
         }
     }
    
    0 讨论(0)
  • 2021-02-12 23:39

    I got it solved easier by doing this:

     tableView.selectRow(at: nil, animated: true, scrollPosition: UITableView.ScrollPosition.top)
    
    0 讨论(0)
  • 2021-02-12 23:46

    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) }
        }
    }
    
    0 讨论(0)
  • 2021-02-12 23:48
    collectionView.indexPathsForSelectedItems?
        .forEach { collectionView.deselectItem(at: $0, animated: false) }
    
    0 讨论(0)
  • 2021-02-12 23:53

    This answer may be useful in swift 4.2

     let selectedItems = followCollectionView.indexPathsForSelectedItems
    
     for (value in selectedItems) {
         followCollectionView.deselectItemAtIndexPath(value, animated:true)
         if let cell = followCollectionView.cellForItemAtIndexPath(value) as? FollowCell {
            cell.checkImg.hidden = true
         }
     }
    
    0 讨论(0)
提交回复
热议问题