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

时间:2016-05-23 00:52:57

标签: ios swift uiswitch

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

//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时应关闭开关。相反,它在传递真实时将其关闭,并且根本不会改变状态。

1 个答案:

答案 0 :(得分:3)

回想一下UISwitch切换最终用户点击的值。

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

删除对setOn的所有来电都将修复您的代码。