简体   繁体   中英

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?

I would override prepareForReuse in your custom cell

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM