【问题标题】:Is it bad to change collection view cell with property observer?使用属性观察器更改集合视图单元格是否不好?
【发布时间】:2024-01-16 23:45:01
【问题描述】:
class SceneCell: UICollectionViewCell {

    override var isSelected: Bool {
        didSet {
            setSelected(bool: isSelected)
        }
    }

    override var isHighlighted: Bool {
        didSet {
            setHighlighted(bool: isHighlighted)
        }
    }

    @IBOutlet weak var thumbnailImageView: UIImageView!

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        self.backgroundColor = .clear
        self.thumbnailImageView.layer.borderColor = UIColor.green.cgColor
        self.thumbnailImageView.layer.masksToBounds = true
        self.thumbnailImageView.clipsToBounds = true
        self.thumbnailImageView.layer.cornerRadius = 8
    }

    func update(with scene: Scene) {

    }

    private func setHighlighted(bool: Bool) {
        if bool {
            self.alpha = 0.5
        } else {
            self.alpha = 1.0
        }
    }

    private func setSelected(bool: Bool) {
        if bool {
            self.thumbnailImageView.layer.borderWidth = 2.5
        } else {
            self.thumbnailImageView.layer.borderWidth = 0
        }
    }
}

在我的代码中,当 isSelected 设置为 true 时,我将图像视图的图层边框宽度更改为 2.5。

当我选择一个单元格并滚动集合视图时,我认为重用该选定单元格时单元格保持选中状态,但重用单元格变为未选中状态。其次,当我回到选中的单元格并重新使用未选中的单元格时,我认为它处于未选中状态。但是单元格会自动设置为选中状态。

集合视图是否自动管理这些?

【问题讨论】:

    标签: ios swift uicollectionview uikit uicollectionviewcell


    【解决方案1】:

    问题的代码运行良好。这是记录单元格的选择并为选中/取消选中状态应用设置的替代解决方案。

    class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
        //......
    
        var selectedIndexPaths = [IndexPath]()
    
        public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            selectedIndexPaths.append(indexPath)
        }
    
        public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
            if let index = selectedIndexPaths.index(of: indexPath) {
                selectedIndexPaths.remove(at: index)
            }
        }
    
        public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            //...
            cell.setSelected(selectedIndexPaths.contains(indexPath)) //Remember to make the cell's setSelected() public.
            //...
        }
    
        //......
    }
    

    【讨论】:

    • 完美解决重用问题?我猜它在没有滚动的情况下工作得很好,是吗?
    • 没有复用问题。我的问题是为什么这段代码运行良好。
    • 滚动时效果很好!
    • 没关系。用属性观察者改变单元格的视图是不是很糟糕?
    • 我认为集合视图会在重用单元格时自动管理选定的索引路径并设置 isSelected 属性。所以效果很好。这样对吗?这是我的怀疑点。