我想设置计时器并每5秒更改一次背景颜色。
我编写了随机颜色的代码,并且它的工作非常完美,但我试着把这个函数放在NSTimer中,我很喜欢。
2016-03-05 14:46:48.774 Boo Adventure [6782:365555] ***终止应用 由于未被捕获的异常' NSInvalidArgumentException',原因: ' - [Boo_Adventure.GameScene update]:发送到的无法识别的选择器 实例0x7fe2cb741ac0'
游戏场景:
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
extension UIColor {
static func randomColor() -> UIColor {
let r = CGFloat.random()
let g = CGFloat.random()
let b = CGFloat.random()
// If you wanted a random alpha, just create another
// random number for that too.
return UIColor(red: r, green: g, blue: b, alpha: 2.5)
}
}
override func didMoveToView(view: SKView) {
Timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "update", userInfo: nil, repeats: false)
func update() {
self.view!.backgroundColor = UIColor.randomColor()
}
}
谢谢!
答案 0 :(得分:2)
这里几个问题:
1)您希望每5秒更改一次颜色,但是将repeats
参数设置为false
,因此您的自定义更新()方法只会执行一次。将repeats
更改为true
。
2)您正在尝试更改视图的背景颜色(SKView)而不是场景的背景颜色。
以下是使用NSTimer
:
override func didMoveToView(view: SKView) {
let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
}
func update(){
backgroundColor = UIColor.randomColor()
}
但NSTimer
不受场景或视图暂停状态的影响,因此在某些情况下可能会让您陷入麻烦。为避免这种情况,您可以使用SKAction
。与SKAction相同的事情看起来像这样:
override func didMoveToView(view: SKView) {
let wait = SKAction.waitForDuration(5)
let block = SKAction.runBlock({
[unowned self] in
self.backgroundColor = UIColor.randomColor()
})
let sequence = SKAction.sequence([wait,block])
runAction(SKAction.repeatActionForever(sequence), withKey: "colorizing")
}
这样,如果您暂停场景或视图,颜色化操作将自动暂停(当场景/视图取消暂停时取消暂停)。
答案 1 :(得分:0)
你的函数update
看起来像是关闭计时器 - 但事实并非如此。取出该功能,使其看起来像这样
override func didMoveToView(view: SKView) {
Timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "update", userInfo: nil, repeats: false)
}
func update() {
self.view!.backgroundColor = UIColor.randomColor()
}
答案 2 :(得分:0)
不知道这是否解决了问题,但根据NSTimer Class Reference,选择器应该有签名:
timerFireMethod:
尝试将update
功能签名更新为
func update(timer: NSTimer)
并更新此行:
Timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "update", userInfo: nil, repeats: false)
为:
Timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "update:", userInfo: nil, repeats: false)