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.
Asked
Active
Viewed 3,204 times
3 Answers
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:

Dharmesh Kheni
- 71,228
- 33
- 160
- 165
-
Happy to help you..:) – Dharmesh Kheni Sep 29 '15 at 05:34
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