Ios 不应该';你不能反其道而行之吗?
我对为什么我的代码的工作方式与我最初认为的相反感到困惑。下面是我的代码当前的工作方式:Ios 不应该';你不能反其道而行之吗?,ios,swift,uiswitch,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 o
//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")
}
我不明白为什么第一个版本有效,但第二个版本无效。当传递false作为第一个参数时,应关闭开关。相反,当传递为true时,它会将其关闭,并且不会改变状态。回想一下,
UISwitch
会在最终用户点击时切换其值
您的开关点击
将与开关在内部切换其值一起被调用。您的第一个代码保持状态不变,因此当开关切换它时,最终结果是切换。但是,您的第二个代码会反转状态,因此当“UISwitch”切换时,开关将保持在其原始状态,因为两个切换会相互抵消
删除对
setOn的所有调用将修复您的代码。我不知道!非常感谢您不,SwitchTap
在交换机切换其状态后被调用。假设开关关闭,用户点击它。开关将自身设置为on并调用开关抽头
。然后SwitchTap
(在Jacob的第二个版本中)将状态设置回off(假)。所以点击开关没有效果(“根本不改变状态”)@robmayoff你是对的,谁先做反转的顺序是无关的,代码还是开关。我编辑了答案,删除了OP的代码在切换之前起作用的内容。您的开关点击
功能是与您添加到UISwitch
的点击手势相关联,还是与“ValueChanged”控制事件相关联?如果是后者,您真的应该重命名该函数,使其不那么混乱。主题外,但阅读起来肯定很有趣: