ios - UICollectionViewCell IBAction 影响多个单元格

标签 ios swift uicollectionviewcell

我有一个 UICollectionView,其中包含附加了 IBAction 的自定义单元格。简而言之,当点击单元格上的 UIStepper 时,它会增加一个值并显示在单元格上的标签中。

我的工作就这么多了,没有太多麻烦。问题是,如果我滚动足够多以将新单元格加载到内存中,则与修改的单元格索引相匹配的单元格将显示与原始值相同的增量值。

Cell1 Cell2 Cell3 --scroll-> Cell4 Cell5 Cell6
  0     1     0                0     1     0

尽管未更改,单元格 5 仍将与单元格 2 的值匹配。

@IBAction func updateValue(sender: AnyObject) {
    // Code to check if plus or minus
    self.valueLabel = value
}

我该如何解决这个问题?

编辑:

细胞类别

protocol ItemCellProtocol {
   fun getValue(value: Double, increment: Bool) -> Double
}

class CustomCollectionViewCell: UICollectionViewCell {
   @IBOutlet weak var stepper: UIStepper!
   @IBOutlet weak var valueLabel : UILabel!
   @IBOutlet weak var image : UIImage!

   var value = 0
   var delegate : ItemCellProtocol?

   @IBAction func updateQuantity(sender: AnyObject) {
      // Code to check if plus or minus
      self.valueLabel = value

      delegate?.getValue(value, increment: true)
   }
}

Collection View Controller

class CustomCollectionViewController : UICollectionViewController {
  var overallValue = 0
  items = [item]() // populated during segue of previous VC

  // CollectionView Delegate classes

  func .. cellForItemAtIndexPath {
    let cell = //instance of CustomCollectionViewCell

     let cellItem : Item = self.items[indexPath.row]

     cell.image = cellItem.image

     cell.delegate = self

     return cell
  }

  func getTotal(value: Double, increment: Bool) -> Double {
     if increment {
       self.overallValue += value
     } else {
       self.overallValue -= value
     }
     return self.total
  }
}

这基本上就是当前类(class)的运作方式。目前我面前没有 Xcode,因此无法提供完整的代码。

最佳答案

UICollectionViewCell 将被 UICollectionView 重用,因此在您的自定义单元格中,在重用之前重置所有 UI 状态

override func prepareForReuse() {
    super.prepareForReuse()
    self.valueLabel.text = "0"
}

关于ios - UICollectionViewCell IBAction 影响多个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803067/

相关文章:

ios - 我的 "App IDs"部分应该是什么样子的?

android - 如果用户向下/向上滑动,不要关闭 Photoswipe

ios - 为什么我从 S3 下载的图像只出现在 1 个人的手机上?

swift - 在 CloudKit Record 中添加引用

objective-c - UITableViewCell 错误中的 UICollectionViewCell 中的 UIImageView

ios - RealmSwift : How to create To-One Relationships properly?

ios - 不重用单元格的 UICollectionView

parameters - Swift 会自动克隆参数吗?

ios - 如何根据数据更改 UICollectionView 单元格宽度

ios - Swift - 当我尝试通过 cellForItem 访问项目时,我的项目为零