UItableviewCell全部取消select
我有一个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 } }
请注意,我也可以使用以下代码select和取消select多个图像
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 }
当在“select”模式下,我可以执行每个单元格的select,并在单元格上显示一个复选标记。 但是,我想要做的是取消button来禁用所有选定的单元格,并删除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 } }
该程序崩溃在这里给我一个致命的错误:意外地发现零,而在解包可选错误
let cell = followCollectionView.cellForItemAtIndexPath(indexP) as! FollowCell
我不知道为什么它有麻烦解开的单元格是我的FollowCell包含checkImg的一个实例。 我已经在didSelectItemAtIndexPath类似的情况下使用它,它似乎工作?
谢谢,
在清除select状态时,并不是所有选定的单元格都可以在屏幕上显示,因此collectionView.cellForItemAtIndexPath(indexPath)
可能返回nil。 既然你有一个压倒性的力量,你会在这种情况下得到一个exception。
你需要修改你的代码来处理潜在的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 } }