【发布时间】:2019-09-01 07:24:00
【问题描述】:
我根据加号和减号按钮计算表格视图单元格中的标签,标签值增加和减少计数,当我向下滚动时,标签在其他单元格上重复,并且单元格中的数据在上下移动时发生变化.任何人请帮我解决这个问题。谢谢
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:CustomTableViewCell = self.customTableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! CustomTableViewCell
cell.plusButton.tag = indexPath.row
cell.plusButton.addTarget(self, action: #selector(BtnPlusPressed(_:)), for: .touchUpInside)
cell.minusButton.tag = indexPath.row
cell.minusButton.addTarget(self, action: #selector(BtnMinusPressed(_:)), for: .touchUpInside)
cell.deviceLabel.text = self.laptop[indexPath.row]
return cell
}
@objc func BtnPlusPressed(_ sender: AnyObject) {
let button = sender as? UIButton
let cell = button?.superview?.superview as? CustomTableViewCell
let indexPath = customTableView.indexPath(for: cell!)
if let text = cell?.countLabel.text, let value = Int(text) {
var counter = value {
didSet {
cell?.countLabel.text = "\(counter)"
print()
}
}
counter += 1
callback?(counter)
}
}
@objc func BtnMinusPressed(_ sender: AnyObject) {
let button = sender as? UIButton
let cell = button?.superview?.superview as? CustomTableViewCell
let indexPath = customTableView.indexPath(for: cell!)
if let text = cell?.countLabel.text, let value = Int(text), value > 0 {
var counter = value {
didSet {
cell?.countLabel.text = "\(counter)"
}
}
counter -= 1
callback?(counter)
}
【问题讨论】:
-
单元正在重用。从顶部出去,从底部进入。和反向。
-
您需要将值存储在底层数据模型中,而不是单元格本身中。这是因为单元格一旦滚动离开屏幕就会被重复使用。根据 cellForRow() 方法中的数据模型设置值。
-
计数器值应该存储在一个数组中,就像您从中获取数据的笔记本电脑数组一样。单元格不应该是您保存计数器值的位置。计数器的值应该在 cellForRow 方法中获取 - 它会在每个即将被重用的单元格中调用。