我正在尝试重载Swift中的touchesBegan函数,但是我遇到了一个奇怪的错误导致XCode崩溃。
我认为问题出在“for touch: AnyObject in touches {
”行,但我在其他课程中使用它并且效果很好。
这是我的代码:
import SpriteKit
class PlayScene: SKScene {
let touchButton = SKSpriteNode(imageNamed:"Touch")
override func didMoveToView(view: SKView!) {
self.backgroundColor = UIColor(hex: 0xD64541)
self.touchButton.size = CGSizeMake(50, 50)
let touchButtonWidth = self.touchButton.size.width
let touchButtonHeight = self.touchButton.size.height
self.touchButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.addChild(self.touchButton)
}
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if self.nodeAtPoint(location) == self.touchButton {
println("button")
}
else {
println("ext")
}
}
}
}
谢谢
答案 0 :(得分:1)
在迭代之前尝试检查touches
是否为nil(适用于我):
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
if let tchs = touches {
for touch: AnyObject in tchs {
let location = touch.locationInNode(self)
if self.nodeAtPoint(location) == self.touchButton {
println("button")
}
else {
println("ext")
}
}
}
}