所以我很难尝试做一些应该很容易的事情,显然我看不出有什么问题。 这是代码:
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
节点内文本的更新。
希望这对您有所帮助。
关于ios - 让 Spritekit 显示存储在变量中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32749009/