UISwitch在swift中无法正常工作

问题描述 投票:0回答:1

我在新的快速项目中采用了UISwitch控件。并且默认状态为storyboard中的Off。我把它当作IBOutlet

@IBOutlet weak var SwitchRemFacility: UISwitch!

我还通过故事板中的Value change事件将其限制为一个方法。

@IBAction func rememberFacilityClick(sender: AnyObject) {
        print(SwitchRemFacility.on)
        if SwitchRemFacility.on {
            SwitchRemFacility.setOn(false, animated: true)
        } else {
            SwitchRemFacility.setOn(true, animated: true)
        }
    }

问题是SwitchRemFacility.on在这里总是回归真实。我已经通过断点检查了,我也将它打印到控制台。任何肝脏将不胜感激。

提前致谢。

ios swift ibaction uiswitch
1个回答
3
投票

当值已经更改时,您正在测试它。 Switch会自行开启和关闭工作。

如果你想手动完成,你可以这样做:

@IBAction func switchChangeVal(sender: AnyObject) {
    let swh : UISwitch = sender as! UISwitch
    if(swh.on){
        swh.setOn(true, animated: true)//But it will already do it. 
    }
    else{
        swh.setOn(false, animated: true)
    }
}

其实不需要代码。但是如果你想要打开或关闭状态,那么你必须做代码。

例如

@IBAction func switchChangeVal(sender: AnyObject) {
    let swh : UISwitch = sender as! UISwitch
    if(swh.on){
        //Do the code for when switch is on
    }
    else{
        //Do the code for when switch is off
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.