How to programmatically put UISwitch in SpriteKit / Skcene

I'm just trying to put a default switch that is already built in Xcode in sKcene. I need to know how to do this quickly or possibly. Thanks.

+1
ios xcode swift
source share
3 answers

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

+6
source share
 // 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) 
0
source share

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") } } 
0
source share

All Articles