Detecting a change in UISwitch

后端 未结 8 1248
暖寄归人
暖寄归人 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: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

提交回复
热议问题