UISwitch 不应该以相反的方式工作吗?

Shouldn't UISwitch work the opposite way?

我很困惑为什么我的代码以与我原先想象的相反的方式工作。以下是我的代码当前的运行方式:

//MARK: Actions
@IBAction func SwitchTap(sender: UISwitch) {
    if mySwitch.on {                           //prints on if turning on
        mySwitch.setOn(true, animated: true)
        print ("switch is on")
    }
    else {
        mySwitch.setOn(false, animated: true)
        print("switch is off")              //prints off if turning off
    }

我认为它应该是这样工作的:

//MARK: Actions
@IBAction func SwitchTap(sender: UISwitch) {
    if mySwitch.on {
        mySwitch.setOn(**false**, animated: true) // should be false instead of true like in the previous example
        print ("switch is on")
    }
    else {
        mySwitch.setOn(**true**, animated: true) //should be true instead of false like in the previous example
        print("switch is off")
    }

我不明白为什么第一个版本有效而​​第二个版本无效。 SetOn 应该在将 false 作为第一个参数传递时关闭开关。相反,它会在传递 true 时将其关闭,并且不会改变状态。

回想一下,UISwitch 在最终用户点击时切换其值。

您的 SwitchTap 与开关一起调用,在内部切换其值。您的第一个代码使状态保持不变,因此当开关切换它时,最终结果是切换。然而,您的第二个代码反转了状态,因此当“UISwitch”切换它时,开关保持其原始状态,因为两个切换相互抵消。

删除对 setOn 的所有调用将修复您的代码。