Ios UICollectionViewCell iAction影响多个单元格
我有一个带有自定义单元格的Ios UICollectionViewCell iAction影响多个单元格,ios,swift,uicollectionviewcell,Ios,Swift,Uicollectionviewcell,我有一个带有自定义单元格的UICollectionView,其中附加了iAction。简而言之,当点击单元格上的UIStepper时,它会增加一个值并显示在单元格上的标签中 这是我在工作中没有太多麻烦。问题是,如果我滚动到足以将新单元格加载到内存中,与被修改单元格的索引匹配的单元格将显示与原始单元格相同的递增值 Cell1 Cell2 Cell3 --scroll-> Cell4 Cell5 Cell6 0 1 0 0 1
UICollectionView
,其中附加了iAction
。简而言之,当点击单元格上的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)
}
}
采集视图控制器
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
}
}
这就是类当前的工作方式。我当前没有Xcode,因此无法提供完整的代码。
UICollectionViewCell
将被UICollectionView
重用,因此在自定义单元格中,在重用之前重置UI的所有状态
override func prepareForReuse() {
super.prepareForReuse()
self.valueLabel.text = "0"
}
在哪里存储单元格的值?您不能将值存储在单元格本身,因为单元格被重用。请为tableView数据源方法添加代码。也就是你增加和存储步进值的地方。谢谢@dopcn的回复。但是,一旦它离开视图,这不会重置原始单元格值吗?@Sawyer05是的,它会重置,这就是收集视图数据源协议所做的