Search code examples
iosswiftibactionuiswitch

UISwitch not working properly in swift


I have taken a UISwitch control in my new swift project. And the default state of this is set as Off from storyboard. I have bounded it as IBOutlet

@IBOutlet weak var SwitchRemFacility: UISwitch!

I have also bounded it to a method by Value change event from storyboard.

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

The Problem is that SwitchRemFacility.on returns always true here. I have checked by breakpoint and also I have printed it to console. Any hep will be appreciated.

Thanks in advance.


Solution

  • You are testing it when value is already changed. Switch will do it's on and off work by it self.

    If you want to do it manually you can do like :

    @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)
        }
    }
    

    Actually no need of code. But if you want to condition on the on or off state then you have to do code.

    For Example

    @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
        }
    }