UICollectionView如何取消选择所有

我有一个FollowVC和FollowCell设置与集合视图。 我可以使用以下代码正确地将所有数据显示到我的uIcollection视图单元格中,没有任何问题。

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FollowCell", forIndexPath: indexPath) as? FollowCell { let post = posts[indexPath.row] cell.configureCell(post, img: img) if cell.selected == true { cell.checkImg.hidden = false } else { cell.checkImg.hidden = true } return cell } } 

请注意,我还可以使用以下代码选择和取消选择多个图像

  func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if deletePressed == true { let cell = collectionView.cellForItemAtIndexPath(indexPath) as! FollowCell cell.checkImg.hidden = false } else { let post = posts[indexPath.row] performSegueWithIdentifier(SEGUE_FOLLOW_TO_COMMENTVC, sender: post) } } func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) as! FollowCell cell.checkImg.hidden = true } 

在“选择”模式下,我可以执行每个单元格的选择,并在单元格上显示复选标记。 但是,我想要做的是取消取消按钮以禁用所有选定的单元格并删除checkImg。

我努力了

  func clearSelection() { print("ClearSelection posts.count = \(posts.count)") for item in 0...posts.count - 1 { let indexP = NSIndexPath(forItem: item, inSection: 0) followCollectionView.deselectItemAtIndexPath(indexP, animated: true) let cell = followCollectionView.cellForItemAtIndexPath(indexP) as! FollowCell cell.checkImg.hidden = true } } 

程序崩溃在这里给我一个致命的错误:在解开可选错误的时候意外地发现了nil

 let cell = followCollectionView.cellForItemAtIndexPath(indexP) as! FollowCell 

我不知道为什么在将单元格展开为包含checkImg实例的FollowCell时遇到问题。 我之前在didSelectItemAtIndexPath中的类似情况中已经使用过它,它似乎有效吗?

谢谢,

当您清除选择状态时,并非所有选定的单元格都在屏幕上,因此collectionView.cellForItemAtIndexPath(indexPath)可能返回nil。 由于你有一个强制转发,在这种情况下你会得到一个例外。

您需要修改代码以处理潜在的nil条件,但您也可以通过使用indexPathsForSelectedItems属性来提高代码的效率。

  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 } }