问题
I have a Swift noobie question on class method calls. I'm building a simple learning app for my kids using Sprite Kit. I have a global variable scoreCount defined in GameScene, where I pretty much do all my game logic such as detect correct answer and increment scoreCount. I also have GameOverScene. On both I show the Score -label. I'm keeping count of scores with the scoreCount-parameter (in GameScene). However as I'm quite new to Swift and Sprite Kit, I'm wondering how should I update the score label in GameViewController? So basically I would like to call GameViewController.updateLabels() from GameScene.
I know this isn't the ideal way but please share your solution concept on this. Thanks!
回答1:
Well. In your GameViewController you have to transform your func in class func like this
class func yourFunc {
//your code
}
To call it from your GameScene just this code :
GameViewController.yourFunc()
Don't forget you are creating a global function so all variables in it have to be global too.
For you label (global):
var label:UILabel = UILabel()
in Your GameViewController:
class GameViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
label.text = "bonjour" // to set the text
label.frame = CGRectMake(0, 0, 100, 100) / set the position AND size CGRectMake (x, y, width, heigth)
label.textColor = UIColor.redColor() // set your color
label.center = CGPointMake(self.view.frame.width/2, self.view.frame.height/2) // set the position from x=0 and y=0
self.view.addSubview(label) // add the label to your screen
I hope it will help you.
来源:https://stackoverflow.com/questions/26449343/global-function-call-in-swift-howto