【发布时间】:2016-01-17 19:52:36
【问题描述】:
我在带有自定义单元格的UIViewController 中使用UITableView。但是,当调用dequeueReusableCellWithIdentifier 时,它有时会创建一个新单元格而不是重用现有单元格。
例如:第一次更新第一个单元格时,会创建一个新单元格,而不是重复使用原始单元格。
我创建了一个图表来帮助更好地说明问题。每个绿色矩形都是应该发生的动作,每个红色矩形都是不应该发生的动作。每个箭头都是对dequeueReusableCellWithIdentifier 的调用。
当UIButton被点击时会出现问题(该操作被多次调用),并且通过“滑动删除”操作,已经滑动的单元格可以被新的第二个单元格覆盖,这使得它出现就像删除按钮随机消失一样。
我该如何解决这个问题?
编辑:
代码自定义单元格
class TableViewCell : UITableViewCell{
@IBOutlet weak var buttonStop: UIButton!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print("newCell")
backgroundColor = color
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func prepareForReuse() {
super.prepareForReuse()
}
var color = UIColor().randomColor()
}
随机颜色扩展代码
extension UIColor {
func randomColor() -> UIColor {
let aRedValue = CGFloat(arc4random()) % 255 / 255
let aGreenValue = CGFloat(arc4random()) % 255 / 255
let aBlueValue = CGFloat(arc4random()) % 255 / 255
return UIColor(red: aRedValue, green: aGreenValue, blue: aBlueValue, alpha: 1)
}
cellForRow 的代码
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! TableViewCell
cell.buttonStop.tag = indexPath.row
cell.buttonStop.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
按钮操作:
func buttonAction(sender: UIButton) {
print("action for cell : \(sender.tag)")
}
我将代码减少到最大,在进一步调查后请注意,由于我的一个错误,按钮打印了相同的文本我写了两次消息^^' 所以剩下的唯一问题是“滑动删除”手势
【问题讨论】:
-
用
cellForRowAtIndexPath方法更新您的问题。还要确保自定义单元格类中的prepareForReuse方法正确重置单元格的状态。
标签: ios uitableview custom-cell