所以我很难做一些应该很容易的事情,显然我看不出有什么问题。这是代码:
import SpriteKit
var money = "0"
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let moneyLabel = SKLabelNode(fontNamed:"Times New Roman")
moneyLabel.text = money;
moneyLabel.fontSize = 14;
moneyLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(moneyLabel)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
money + 1
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
这应该做的是让一个标签显示一个变量,当用户触摸屏幕时,变量变化1,每次按下1。标签应该随着变量的变化而变化。我该怎么做呢?
问题
您只是将1
添加到money
money + 1
这个代码:- 不改变
money
属性 - 不改变您的
moneyLabel
中的文本 - 是非法的,因为你不能对
String
和Int
求和
这段代码应该完成
import SpriteKit
class GameScene: SKScene {
private var money = 0 {
didSet {
self.moneyLabel?.text = money.description
}
}
private var moneyLabel : SKLabelNode?
override func didMoveToView(view: SKView) {
let moneyLabel = SKLabelNode(fontNamed:"Times New Roman")
moneyLabel.text = money.description
moneyLabel.fontSize = 14
moneyLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
self.addChild(moneyLabel)
self.moneyLabel = moneyLabel
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
money += touches.count
}
}
解释
1)
您可以看到,我在money
属性中添加了一个观察者(顺便说一下,我使它成为Int
属性,而不是您代码中的String
!)
didSet {
self.moneyLabel?.text = money.description
}
由于观察者的作用,每次货币发生变化时,moneyLabel
节点都会被检索并更新其文本。
2)
在didMoveToView
结束时,我将moneyLabel
保存到实例属性
self.moneyLabel = moneyLabel
,这样我就可以很容易地检索到
(我们在前面已经看到了)3)
最后在touchesBegan
中,我只是将money
属性增加接收触摸的数量。
money += touches.count
多亏了观察者,每次对money
属性的更改都会触发对moneyLabel
节点内文本的更新。
这里有三个问题:
-
money
应该是一个Int
,所以你可以添加。 - 您实际上没有将
money
更新为新值。 - 除了
money
之外,您还需要更新标签。
看看下面的变化;每个注释解释了为什么需要更改:
import SpriteKit
class GameScene: SKScene {
var money = 0 //now an Int, so we can add to it later
let moneyLabel = SKLabelNode(fontNamed:"Times New Roman") //keep this around so we can update it later
override func didMoveToView(view: SKView) {
moneyLabel.text = String(money) //convert money to a String so we can set the text property to it
moneyLabel.fontSize = 14
moneyLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
self.addChild(moneyLabel)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
money = money + 1 //update money to itself + 1
moneyLabel.text = String(money) //update the label, too
}
}
}