when I use let
UISwitch
replace lazy var
UISwitch
in UITableViewCell
like this:
let trigger: UISwitch = {
let sw = UISwitch()
sw.addTarget(self, action: #selector(onTriggerChanged(sender:)), for: .valueChanged)
return sw
}()
I found the function onTriggerChanged
never called, so I do some test, here is my test code:
class TestCell: UITableViewCell {
lazy var trigger: UISwitch = {
let sw = UISwitch()
print("trigger (self)")
sw.addTarget(self, action: #selector(onTriggerChanged(sender:)), for: .valueChanged)
return sw
}()
var trigger2: UISwitch = {
let sw = UISwitch()
print("trigger2 (self)")
sw.addTarget(self, action: #selector(onTriggerChanged(sender:)), for: .valueChanged)
return sw
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let trigger3: UISwitch = {
let sw = UISwitch()
print("trigger3 (self)")
sw.addTarget(self, action: #selector(onTriggerChanged(sender:)), for: .valueChanged)
return sw
}()
contentView.addSubview(trigger)
contentView.addSubview(trigger2)
contentView.addSubview(trigger3)
}
}
print message is:
trigger <TestCell: 0x......>
trigger2 (Function)
trigger3 <TestCell: 0x......>
and trigger2 valueChanged event not called.
so what difference of self in trigger/trigger2/trigger3
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…