簡體   English   中英

用屬性觀察器更改集合視圖單元格是否不好?

[英]Is it bad to change collection view cell with property observer?

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。

當我選擇一個單元格並滾動收集視圖時,我認為重用該選定單元格時該單元格仍處於選定狀態,但是重用單元格變為未選定狀態。 其次,當我返回到所選單元格並重新使用未選中的單元格時,我認為它處於未選中狀態。 但是單元格會自動設置為選中狀態。

收集視圖是否自動管理這些內容?

問題的代碼運行正常。 這是記錄單元格選擇並為選定/取消選定狀態應用設置的替代解決方案。

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.
        //...
    }

    //......
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM