我在SpriteKit上使用Xcode 7 Beta在游戏中放置了一些按钮,它们始终可见,我想让它们在游戏开始时隐身,并在游戏结束时可见。我尝试使用Bool,但由于它们位于不同的文件(类)中而无法工作。启动游戏和游戏的功能在GameScene.swift中,按钮的功能在GameViewController.swift中。
我用游戏开始的代码是:
var isStarted = false
func start() {
isStarted = true
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if isGameOver {
restart()
} else !isStarted {
start()
所以游戏从触摸屏开始。
我用游戏结束的代码是:
var isGameOver = false
func gameOver() {
isGameOver = true
}
按钮在GameViewController.swift中作为发件人:UIButton。
@IBAction func facebookShare(sender: UIButton){
let facebookShare : SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
self.presentViewController(facebookShare, animated: true, completion: nil)
}
@IBAction func twitterShare(sender: UIButton) {
let twitterShare : SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
self.presentViewController(twitterShare, animated: true, completion: nil)
}
@IBAction func leaderboard(sender: UIButton) {
}
@IBAction func removeAds(sender: UIButton) {
}
如你所见,我没有完成两个按钮,无论如何我会在此之后 我希望你会有所帮助,因为我是初学者
答案 0 :(得分:1)
好的,下面你会找到一种方法如何将事件发送到正在收听它的任何对象....
class ClassWithButtonsInIt: UIViewController {
@IBOutlet weak var buttonOne: UIButton!
@IBOutlet weak var buttonTwo: UIButton!
@IBOutlet weak var buttonThree: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("hideButtonsEvent"), name: "hideButtonsEvent", object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
private func hideButtonsEvent (notification: NSNotification) {
buttonOne.hidden = true
buttonTwo.hidden = true
buttonThree.hidden = true
}
}
class ClassWithoutButtonsThatTriggersTheHidingEvent {
private func triggerdFunctionThatHidesButtonsInOtherClass () {
NSNotificationCenter.defaultCenter().postNotificationName("hideButtonsEvent", object: nil)
}
}
修改强>
是的,没错,抱歉我的代码中也有一个小错误:-) 请更改此行:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("hideButtonsEvent"), name: "hideButtonsEvent", object: nil)
到这一行(参见hideButtonsEvent后面的双点):
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("hideButtonsEvent:"), name: "hideButtonsEvent", object: nil)
这一行:
private func hideButtonsEvent (notification: NSNotification) {
到此行(删除私有修饰符):
func hideButtonsEvent (notification: NSNotification) {