UICollectionView选择了单元格问题

时间:2018-03-15 16:48:24

标签: swift uicollectionview

我有UICollectionView,我选择带有didSelectItemAt的单元格并使用didDeselectItemAt取消选择但是已替换选定的单元格

enter image description here

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
        }

    }

2 个答案:

答案 0 :(得分:1)

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

您需要创建indexPath数组,它将存储选定的indexPath。

var arrSelectedIndexPath = [IndexPath]()

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

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

didSelect方法中,您需要添加以下代码,这些代码也与上述逻辑相同,但只需添加或删除indexPath。

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

我希望这个解决方案适合你。

答案 1 :(得分:0)

尝试以下代码。在“didSelectItemAt”函数中还添加了逆向条件:

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

同样,在“didDeselectItemAt”中添加以下条件:

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

每当我们重用单元格时都会出现此问题。上面的代码可能会帮助你!!