持久化UITableViewCell子类属性

时间:2016-05-27 23:04:12

标签: ios iphone swift uicollectionviewcell

我有一个UITableViewCell子类,其中包含Bool。此属性应该保持(当单元格可见时),但是,我似乎已将其设置为在调用collectionView:cellForItemAtIndexPath:时重置属性。实施例

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
}

我是否需要在someBool方法中设置init?设计这个的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

我会覆盖自定义单元格中的prepareForReuse

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