UICollectionView 选定的单元格问题 [英] UICollectionView selected cells issue

查看:21
本文介绍了UICollectionView 选定的单元格问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 UICollectionView,我用 didSelectItemAt 选择了单元格并用 didDeselectItemAt 取消选择但选定的单元格被替换

I have UICollectionView, i am selected cell with didSelectItemAt and deselect with didDeselectItemAt but selected cells are replaced

https://im4.ezgif.com/tmp/ezgif-4-2715e62591.gif

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

       let cell = collectionView.cellForItem(at: indexPath)

       // print(indexPath)

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




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

    }

    func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
        return true
    }

    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)

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


        if cell?.isSelected == false {
            cell?.backgroundView = collectionInactive
        }

    }

推荐答案

我也做过同样的事情,我有以下解决方案.

I have also worked on same things, I have following solution for that.

您需要创建一个 indexPath 数组,用于存储选定的 indexPath.

You need to create array of indexPath which will store selected indexPath.

var arrSelectedIndexPath = [IndexPath]()

cellForRowAtItem 方法中添加以下代码,将检查 arrSelectedIndexPath 是否包含 indexPath 然后显示选定的活动背景,否则显示非活动背景.

In cellForRowAtItem method add following code which will check if arrSelectedIndexPath contains indexPath then display selected active background else display inactive background.

if arrSelectedIndexPath.contains(indexPath) {
    cell?.backgroundView = collectionActive
} else {
    cell?.backgroundView = collectionInactive
}

didSelect 方法中,你需要添加以下代码,与上述逻辑相同,但只需添加或删除 indexPath.

In didSelect method you need to add following code which also same as above logic, but just add or remove indexPath.

if arrSelectedIndexPath.contains(indexPath) {
    cell?.backgroundView = collectionInactive
    arrSelectedIndexPath.remove(at: arrSelectedIndexPath.index(of: indexPath)!)
} else {
    cell?.backgroundView = collectionInactive
    arrSelectedIndexPath.append(indexPath)
}

我希望这个解决方案对你有用.

I hope this solution work for you.

这篇关于UICollectionView 选定的单元格问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆