【问题标题】:UISwitch not working properly in swiftUISwitch 在 swift 中无法正常工作
【发布时间】:2015-10-05 06:04:17
【问题描述】:

我在我的新 swift 项目中采用了 UISwitch 控件。并且它的默认状态设置为故事板中的Off。我已将其限制为 IBOutlet

@IBOutlet weak var SwitchRemFacility: UISwitch!

我还通过情节提要中的值更改事件将其绑定到一个方法。

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

问题是 SwitchRemFacility.on 在这里总是返回 true。我已经通过断点进行了检查,并将其打印到控制台。任何 hep 将不胜感激。

提前致谢。

【问题讨论】:

    标签: ios swift ibaction uiswitch


    【解决方案1】:

    当值已经改变时,你正在测试它。 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
        }
    }
    

    【讨论】:

    • 如果我只想开启和关闭条件,您的意思是不需要值更改事件?
    • @Max 是的。您无需手动更改该值。 Switch会自己做
    • 您可以打印 true 或 false 的值并处理 true 或 false 条件。无需更改开关状态。
    • @Max 更新了答案。希望对你有帮助。
    • 是的。谢谢你。我忘记了值更改后触发了值更改事件。
    猜你喜欢
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    相关资源
    最近更新 更多