簡體   English   中英

Swift在UICollectionViewCell屬性上運行didSet,但不更新UI

[英]Swift didSet on UICollectionViewCell property running, but not updating UI

我有一個自定義的UICollectionViewCell ,它可以響應選擇事件更改其外觀,並且應該也可以響應其他屬性更改來更改其外觀,但不能。

class NumberCell: UICollectionViewCell {
    let numberLabel = UILabel()

    override var selected: Bool {
        didSet {
            // Updates as expected
            contentView.backgroundColor = self.selected ? UIColor.redColor() : UIColor.clearColor()
        }
    }

    var number: Int? {
        didSet {
            // Sets and shows the text in the number label as expected when cell is first initialised
            if let number = number {
                numberLabel.text = String(number)
            }
        }
    }

    var isCrossedOut: Bool = false {
        didSet {
            // Sets and displays correct values on initialisation, but later
            // stops updating display
            contentView.backgroundColor = self.isCrossedOut ? UIColor.blackColor() : UIColor.clearColor()
        }
    }

    // ...
}

單元格的選定狀態會很好地更新,但是每當我執行cell.isCrossedOut = true ,我都可以看到代碼正在運行,但是我看不到背景顏色實際上發生了變化,即使它看起來使用的邏輯完全相同。選擇屬性觀察器。

我可以通過執行collectionView.reloadData() (不接受重新加載整個集合視圖)或collectionView.reloadItemsAtIndexPaths([...]) (我想或多或少可以接受collectionView.reloadItemsAtIndexPaths([...])來觸發視覺更新。動態更新用戶界面。

編輯

這就是我更新划線屬性的方式:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    if shouldBeCrossedOut(indexPath) {
        let cell = self.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! NumberCell
        cell.isCrossedOut = true
    }
}

更換:

self.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! NumberCell

帶有:

self.collectionView?.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as! NumberCell

self.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! NumberCell self.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! NumberCell是一種數據源方法,您可以重寫該方法self.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! NumberCell集合視圖提供一個單元格(即,它將始終返回一個新實例化或新出列的單元格,從而返回當前不在屏幕上的一個單元格)。 self.collectionView?.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as! NumberCell self.collectionView?.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as! NumberCell是一個實例方法,它將在給定的索引路徑處返回對當前單元格的引用。 情節提要與該問題無關。 您可以在此處查看具有有效代碼而沒有IB的游樂場代碼。

暫無
暫無

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

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