1

I have a custom UICollectionViewCell that changes its appearance in response to selection events, and should change its appearance in response to other property changes, too, but doesn't.

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()
        }
    }

    // ...
}

The selected state for the cell updates nicely, but whenever I do cell.isCrossedOut = true, I can see the code running, but I don't see the background colour actually changing, even though it seems to be using exactly the same logic as the selection property observer.

I can trigger a visual update by doing collectionView.reloadData() (not acceptable to reload the entire collection view), or collectionView.reloadItemsAtIndexPaths([...]) (more or less acceptable I guess), but I really would prefer to update the UI dynamically.

EDIT

This is how I update the crossed out property:

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

1 回答 1

2

代替:

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?.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as! NumberCell是一个实例方法,它将返回对给定索引路径中当前单元格的引用。故事板与此问题无关。您可以在此处查看具有有效代码且没有任何 IB 的操场代码。

于 2016-02-14T03:33:35.027 回答