我在下面有这个代码,我只是想做一个简单的加法游戏,当你点击时打印出来的钱。我已将它设置为打印出0 + 5的currentMoney变量,依此类推,但我无法通过它更改标签。
我尝试在触摸中设置myLabel.text = String(currentMoney)
,但它不会更新myLabel
,我该如何实现?
import SpriteKit
var currentMoney = 0
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = String(currentMoney)
myLabel.fontSize = 45
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
self.addChild(myLabel)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
currentMoney = currentMoney + 5
print(currentMoney)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
答案 0 :(得分:1)
您无法更改文本,因为您无法在moveToView函数外部访问标签。试试这个:
import SpriteKit
var currentMoney = 0
var myLabel: SKLabelNode! //made it globally
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = String(currentMoney)
myLabel.fontSize = 45
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
self.addChild(myLabel)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
currentMoney = currentMoney + 5
myLabel.text = String(currentMoney)
print(currentMoney)
}
答案 1 :(得分:0)
您可以观察currentMoney
变量的变化并采取适当的措施(更新标签的文本属性)。为此,您可以将标签设置为场景的属性,并使用didSet
属性观察器,如下所示:
import SpriteKit
class GameScene: SKScene {
var currentMoney = 0 {
didSet{
myLabel.text = String(currentMoney)
}
}
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
override func didMoveToView(view: SKView) {
/* Setup your scene here */
myLabel.text = String(currentMoney)
myLabel.fontSize = 45
myLabel.position = CGPoint(x:frame.midX, y: frame.midY)
self.addChild(myLabel)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
currentMoney = currentMoney + 5
}
}
答案 2 :(得分:0)
class GameScene: SKScene {let myLabel = SKLabelNode(fontNamed:"Chalkduster") var currentMoney = 0 override func didMoveToView(view: SKView) { /* Setup your scene here */ /* Setup your scene here */ myLabel.text = String(currentMoney) myLabel.fontSize = 45 myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)) self.addChild(myLabel) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ currentMoney = currentMoney + 5 print(currentMoney) myLabel.text = String(currentMoney) } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ }
}