Detecting a change in UISwitch

后端 未结 8 1245
暖寄归人
暖寄归人 2021-02-18 14:19

This sounds trivial but I\'m noticing some weirdness. I\'ve wired up a handler for the Value Changed event of a UISwitch. What I would expect is that each time the hand

相关标签:
8条回答
  • 2021-02-18 15:07

    Log the last state so you can tell if its changed state or has been triggered with the same state.

    0 讨论(0)
  • 2021-02-18 15:12

    In iOS 11 a new UISwitch bug was introduced so I don't recommend subscribing to value changed events. Otherwise your callback will be triggered every time UISwitch's isOn attribute changes programmatically.

    Instead:

    1) Subscribe for touch up inside event:

    let switch = UISwitch()
    switch.addTarget(self, action: #selector(onSwitchValueChanged), for: .touchUpInside)
    

    2) Implement the callback method:

    func onSwitchValueChanged(_ switch: UISwitch) {
    
    }
    

    3) And now when you programmatically change isOn value, it won't trigger onSwitchValueChanged method.

    switch.isOn = !switch.isOn // 'onSwitchValueChanged' is not triggered

    0 讨论(0)
提交回复
热议问题