3

I simply am trying to put the default switch that is already built in Xcode in a sKcene. I need to know how to do this in swift or is it possible Thanks.

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165

3 Answers3

7

Yes it is possible. Just use this code in your SKScene class:

override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    let switchDemo = UISwitch(frame:CGRectMake(150, 300, 0, 0))
    switchDemo.on = true
    switchDemo.setOn(true, animated: false)
    switchDemo.addTarget(self, action: "switchValueDidChange:", forControlEvents: .ValueChanged)
    self.view!.addSubview(switchDemo)
}

Helper method:

func switchValueDidChange(sender:UISwitch!)
{
    if (sender.on == true){
        print("on")
    }
    else{
        print("off")
    }
}

Result:

enter image description here

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
1

Updated to swift 5

override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    let switchDemo = UISwitch(frame:CGRect(x: 150, y: 300, width: 0, height: 0))
    switchDemo.isOn = true
    switchDemo.setOn(true, animated: false)
    switchDemo.addTarget(self, action: #selector(switchValueDidChange(_:)), for: .valueChanged)
    self.view!.addSubview(switchDemo)
}

Helper method:

@objc func switchValueDidChange(_ sender: UISwitch!) {
    if (sender.isOn == true){
        print("on")
    }
    else{
        print("off")
    }
}
DaniChi
  • 301
  • 3
  • 12
0
// Set the desired frame  of switch here

let onOffSwitch:UISwitch = UISwitch(frame:CGRectMake(2, 2, 30, 30))

//assign an action 
onOffSwitch.addTarget(self, action: "onOffSwitchTapped:", forControlEvents: UIControlEvents.ValueChanged)

//Add in required view
self.view.addSubview(onOffSwitch)
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
A For Aj
  • 1
  • 2