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