ios - 点击时切换 UICollectionView Cell 的选择/取消选择状态 - Swift

标签 ios swift uicollectionview

所以首先,我已经坚持了几天,花了一整天的时间阅读并尝试了 Stack Overflow 上的许多选项,但没有成功

我想要完成的事情听起来很简单,在我看来它应该可以工作 https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionViewDelegate_protocol/#//apple_ref/occ/intfm/UICollectionViewDelegate/collectionView:shouldHighlightItemAtIndexPath :

基本上我想要实现的是在点击时切换 UICollectionView 单元格的选定状态。

第一次点击 - 将单元格置于选中状态并将背景颜色更改为白色。

第二次点击 - 将单元格发送到取消选择状态并更改背景颜色以清除

View Controller -

 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 来解决这个问题,但仍然没有运气......

有什么我想念的吗? 或者是否有任何已知的解决方法? 任何帮助将不胜感激!

最佳答案

使用 shouldSelectItemAt 并检查 Collection View 的 indexPathsForSelectedItems 属性以确定是否应选择或取消选择单元格。

func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
    if let indexPaths = collectionView.indexPathsForSelectedItems, indexPaths.contains(indexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        return false
    }

    return true
}

关于ios - 点击时切换 UICollectionView Cell 的选择/取消选择状态 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37222260/

相关文章:

objective-c - 带有动画的 UICollectionView reloadSections

iphone - 更改UIButton文本的颜色和对齐方式

ios - 使用点击手势时无法访问表格 View

java - Realm :记录顺序已更改

ios - 如何从 UITableViewCell 上的自定义 Collection View 单元格推送 VC?

ios - 方法没有覆盖父类(super class)中的任何函数(覆盖 func collectionView)

javascript - 如何在云功能中获取 firebase 数据库数据?

iphone - 使用 jenkins xcode 构建插件构建时出现代码签名错误

ios - 横向导航 Controller ,弹出向上滚动

swift - 代码仅从 Firebase 中的数据中检索一个值