在我的习惯UITableViewCell
设置属性时,如果没有标签,它将创建一个标签并设置文本等。如果标签已经存在,它不应该做任何事情。奇怪的是,当我第一次点击单元格时,它会创建应有的标签。但是当我再次点击单元格时,标签消失了。我已经在一个干净的项目中重新创建了它,并且正在发生同样的事情。这种奇怪行为的原因是什么?
自定义表视图单元:
class TableViewCell: UITableViewCell {
var numberLabel: UILabel!
var views = [String: UILabel]()
var number: Int = 5 {
didSet {
println("AMOUNT: Accessed")
if numberLabel == nil {
println("AMOUNT: Amount is nil")
// Create amount label
numberLabel = UILabel()
if number > 0 { numberLabel.text = String(number) }
numberLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.addSubview(numberLabel)
views["amount"] = numberLabel
// Amount label constraints
contentView.addConstraint(NSLayoutConstraint(item: numberLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[amount(40)]-8-|", options: nil, metrics: nil, views: views))
} else {
println("AMOUNT: Nothing should be changing or happening \n")
}
}
}
required init(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
}
视图控制器:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var items = [Int]()
var amount = 0
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: "cell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 }
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as TableViewCell
cell.number = amount
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
amount++
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
编辑:作为对评论的回应,我的控制台显示:
NUMBER: Accessed
NUMBER: Number is nil
NUMBER: Accessed
NUMBER: Number is nil << label shows "1"
NUMBER: Accessed
NUMBER: Nothing should be changing or happening << label disappears.
NUMBER: Accessed
NUMBER: Nothing should be changing or happening << label shows "1" again
NUMBER: Accessed
NUMBER: Nothing should be changing or happening << label disappears.
NUMBER: Accessed
NUMBER: Nothing should be changing or happening << label shows "1" again
NUMBER: Accessed
NUMBER: Nothing should be changing or happening << label disappears.
我还将背景更改为一种颜色,它就消失了。我想这与oldValue
didSet 的有关。当willSet
我将值更改为newValue
. 但是,当我使用“旧值”时,什么都没有发生。