Search code examples
xcodeswiftswitch-statementwatchkit

Don't know why the switch control always send false Value


I make a simple WKInterface with a switch control and make a function for that switch to show up the value of switch like this: enter image description here

I don't know why when test the switch,the result I received always false? please explain and show me how to fix. As I thought the out put of that switch will change from false to true and move on like that.. What's wrong in here? or the Xcode's bug with switch?


Solution

  • Try this:

    1. First declare outlet for switch like this:

        @IBOutlet weak var mySwitch: UISwitch!
      
    2. In viewDidLoad implement listener (target-action):

      override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
      
            mySwitch.addTarget(self, action: "switchChangedValue:", forControlEvents: UIControlEvents.ValueChanged)
      }
      
    3. Declare this function where you will get response every time switch value is changed:

      func switchChangedValue(sender:UISwitch){
       if sender.isKindOfClass(UISwitch){
          if sender.on {
              println("Switch is ON")
              println("\(sender.on)")
          } else {
              println("Switch is OFF")
              println("\(sender.on)")
          }
      }
      

      }