ios - UICollectionView 选择和取消选择

标签 ios swift uicollectionview

我有 UICollectionView 2 行 10+ 个单元格。 默认取消选择。当我点击它时它会被选中,但当我再次点击时不会取消选择。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print(indexPath)


   let cell = collectionView.cellForItem(at: indexPath)


    let collectionActive: UIImageView = {
        let image=UIImageView(image: #imageLiteral(resourceName: "collectionActive"))
        image.contentMode = .scaleAspectFill
        return image
    }()

    let collectionInactive: UIImageView = {
        let image=UIImageView(image: #imageLiteral(resourceName: "collectionInactive"))
        image.contentMode = .scaleAspectFill
        return image
    }()


    if cell?.isSelected == true {
        cell?.backgroundView = collectionActive
    }else{
        cell?.backgroundView = collectionInactive
    }

}

如何解决这个问题?

最佳答案

在viewDidLoad()中

collectionView.allowsMultipleSelection = true;

后记我实现了这些方法

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCell
    cell.toggleSelected()
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCell
    cell.toggleSelected()
}

终于上课了

class MyCell : UICollectionViewCell {

    func toggleSelected ()
    {
        if (selected){
            backgroundColor = UIColor.redColor()
        }else {
            backgroundColor = UIColor.whiteColor()
        }
    }

}

关于ios - UICollectionView 选择和取消选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49303123/

相关文章:

ios - 在 iOS 应用程序中在哪里存储全局常量?

ios - 如何在 iOS 中以编程方式在日历中添加事件的超链接而不显示实际 URL?

ios - Swift 3 iOS 10 - 带有图像和文本的 UICollectionView 无法正确显示

ios - UICollectionViewCell contentView 填充

iphone - 不显示阿拉伯语键盘

ios - iOS 7 中的屏幕截图

ios - Swift - 更改幻灯片的大小以删除 tableView 中的按钮

ios - 我怎样才能在一个额外的功能中外包这种重复的代码味道? iOS Swift 函数

ios - 通用的 UITableViewDelegate 和 UITableViewDataSource

ios - UICollectionView 未显示且未调用委托(delegate)/数据源方法