JHof JHof - 6 months ago 30
iOS Question

Persist UITableViewCell subclass property

I have a

UITableViewCell
subclass that holds a
Bool
. This property should persist (while the cell is visible), however, I seem to have it set up so that when
collectionView:cellForItemAtIndexPath:
is called, the property is reset. Example

class CellClass: UITableViewCell {

var someBool: Bool = false

func doSomethingWithBool() {
if someBool {
thing1()
someBool = false
} else {
thing2()
someBool = true
}
}
}



class CollectionView: UICollectionView {

@IBAction func buttonPressed() {
// Do some things

// cellForItemAtIndexPath called again here
self.collectionView?.reloadItemsAtIndexPaths(paths)
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CellClass

// Everything else

if collectionViewProperty {
// This doesn't work right because someBool is reset to false
cell.doSomething()
}

return cell
}


Do I need to set
someBool
in an
init
method? What is the correct way to design this?

Answer

I would override prepareForReuse in your custom cell

override func prepareForReuse() {
    super.prepareForReuse()
    someBool = false
}
Comments