【发布时间】:2015-12-26 10:52:00
【问题描述】:
我只是想将已经内置在 Xcode 中的默认开关放在 sKcene 中。我需要知道如何快速做到这一点,或者是否有可能谢谢。
【问题讨论】:
我只是想将已经内置在 Xcode 中的默认开关放在 sKcene 中。我需要知道如何快速做到这一点,或者是否有可能谢谢。
【问题讨论】:
是的,这是可能的。只需在 SKScene 类中使用此代码:
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)
}
辅助方法:
func switchValueDidChange(sender:UISwitch!)
{
if (sender.on == true){
print("on")
}
else{
print("off")
}
}
结果:
【讨论】:
更新到 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)
}
辅助方法:
@objc func switchValueDidChange(_ sender: UISwitch!) {
if (sender.isOn == true){
print("on")
}
else{
print("off")
}
}
【讨论】:
// 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)
【讨论】: