首先,我已经在这个问题上坚持了几天,并花了一整天的时间阅读并尝试了 Stack Overflow 上的许多选项,但并没有成功
我想要完成的事情听起来很简单,并且浏览了苹果文档,在我看来它应该可行https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionViewDelegate_protocol/#//apple_ref/occ/intfm/UICollectionViewDelegate/collectionView:shouldHighlightItemAtIndexPath https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionViewDelegate_protocol/#//apple_ref/occ/intfm/UICollectionViewDelegate/collectionView:shouldHighlightItemAtIndexPath:
基本上我想要实现的是点击时切换 UICollectionView Cell 的选定状态。
第一次点击 - 将单元格置于选定状态并将背景颜色更改为白色。
第二次点击 - 将单元格置于取消选择状态并将背景颜色更改为清除
视图控制器 -
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as? CollectionViewCell {
cell.cellImage.image = UIImage(named: images[indexPath.row])
return cell
} else {
return CollectionViewCell()
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
cell.toggleSelectedState()
}
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
cell.toggleSelectedState()
}
}
Cell -
func toggleSelectedState() {
if selected {
print("Selected")
backgroundColor = UIColor.whiteColor()
} else {
backgroundColor = UIColor.clearColor()
print("Deselected")
}
}
我遇到的问题是,当点击已选择的单元格时,不会调用 didDeselectItemAtIndexPath,但如果我点击另一个单元格,它将被调用并选择新单元格...
我尝试过检查 shouldSelectItemAtIndexPath 和 shouldDeselectItemAtIndexPath 中的选定状态,我什至尝试编写一个 tapGesture 来解决这个问题,但仍然没有运气......
我缺少什么吗?
或者有任何已知的解决方法吗?
任何帮助将不胜感激!