UICollectionViewCell选择后不更新视图

时间:2019-01-14 21:20:38

标签: ios uicollectionview

有一个问题,其中:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
选择了 时会调用

,但是我无法通过此方法更改任何单元格属性。

我创建了一个新项目,其中的UICollectionViewController被精简,以在选中时更改单元格的背景颜色。它也不起作用。在这里:

import UIKit

private let reuseIdentifier = "Cell"

class CollectionViewController: UICollectionViewController {

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 5
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

    cell.backgroundColor = UIColor.blue

    return cell
}

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = self.collectionView(self.collectionView, cellForItemAt: indexPath)
    cell.backgroundColor = UIColor.green
}

}

我在情节提要中所做的唯一一件事就是删除标准的View Controller,并将其替换为UICollectionViewController,创建UICollectionViewController的子类,然后将情节提要中的控制器设置为该类。

此外,我可以确认从didSelectItemAt方法内部调用该方法时,该方法返回了单元格的索引路径:

self.collectionView.indexPathsForSelectedItems

2 个答案:

答案 0 :(得分:1)

您使用了错误的API。 从不调用委托方法collectionView(_ cellForItemAt:,使用cellForItem(at:

if let cell = collectionView.cellForItem(at: indexPath) {
   cell.backgroundColor = UIColor.green
}

但是请注意,此更改不是持久的。当用户滚动时,颜色将变回蓝色。

答案 1 :(得分:0)

您可以通过以下方式实现

ViewController

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColoursViewCell", for: indexPath) as! ColoursViewCell
    return cell
}

UICollectionViewCell

class ColoursViewCell: UICollectionViewCell {
    @IBOutlet var photoImageView: UIImageView?

    override var bounds: CGRect {
        didSet {
            self.layoutIfNeeded()
        }
    }

    override var isSelected: Bool{
        didSet{
            if self.isSelected{
                self.photoImageView?.backgroundColor = UIColor.random
            }else{
                self.photoImageView?.backgroundColor = UIColor.lightGray
            }
        }
    }
}

您可以从我在GitHub中拥有的此链接中获得示例项目 https://github.com/hadanischal/RandomColors/tree/develop

相关问题