2016-05-14 135 views
0

因此,首先我已经停留了几天,花了整整一天的时间阅读并尝试了很多堆栈溢出的选项,但对我的成功没有帮助切换UICollectionView单元格的选择/取消选择状态 - Swift

什么,我试图完成听起来很简单,并打算在我看来,苹果的文档超过它应该工作 https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionViewDelegate_protocol/#//apple_ref/occ/intfm/UICollectionViewDelegate/collectionView:shouldHighlightItemAtIndexPath

基本上我想要实现切换一个UICollectionView的选中状态自来水单元。

第一次点击 - 将单元格发送到选定状态并将背景颜色更改为白色。

第二抽头 - 小区发送到取消选择状态和变化的背景色清除

的ViewController -

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

细胞 -

func toggleSelectedState() { 
    if selected { 
     print("Selected") 
     backgroundColor = UIColor.whiteColor() 
    } else { 
     backgroundColor = UIColor.clearColor() 
     print("Deselected") 
    } 
} 

时遇到的问题是didDeselectItemAtIndexPath不会在点击已经选择的单元格时被调用,尽管如果我点击另一个单元格,它会被调用并选择新单元格...

我曾尝试在shouldSelectItemAtIndexPath检查选择的状态& shouldDeselectItemAtIndexPath,我甚至试着写一个tapGesture来解决这个问题,仍然没有运气...

有我丢失的东西? 或者是否有任何已知的解决方法呢? 任何帮助将不胜感激!

+1

当点击同一个单元格时,它必须再次调用'didSelectItemAtIndexPath'。请检查 – Shubhank

回答

0

也许你可以创建一个与单元格具有相同边界的UIButton(),并确定按钮中的选择。然后在按钮的轻击操作中,您可以执行某些操作以“分离”选中的单元格。

+0

啊当然!甚至没有想到... 没有完全按照我希望的方式工作,但我用通知让它工作 谢谢! – Brrrrryce

0

您可以将UICollectionView的allowsMultipleSelection属性设置为YES(true),那么集合视图将不会取消选择以前的项目。

相关问题