我正在尝试创建 SKSpriteNode 的子类,它可以检测用户交互(点击、双击并按住),然后遵循委托。在我看来,这是一个相对常见的需求,但是:
- 该代码无法在不触发单击的情况下检测双击。
- 我根本没有找到检测按住/长按操作的方法。
我这一切都错了吗?我不禁觉得 SpriteKit 应该有一些标准来处理如此基本的事情。我知道有 UIGestureRecognizer,但它似乎与特定的 SKNodes 而不是 UIViews 非常兼容。
这是我目前所拥有的。根据 Apple 的示例,我在主类文件中拥有所有非特定于设备的代码:
import SpriteKit
enum ActionType: Int {
case Single
case Double
case Hold
}
protocol EnvironmentElementDelegate {
func handleActionOnElement(element: EnvironmentElement, actionType: ActionType)
}
class EnvironmentElement: SKSpriteNode {
let delegate: EnvironmentElementDelegate!
init(imageNamed: String, elementNamed: String, delegate: EnvironmentElementDelegate) {
self.delegate = delegate
let texture = SKTexture(imageNamed: imageNamed)
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
self.name = elementNamed
userInteractionEnabled = true
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
...然后将所有特定于 iOS 的代码放在单独的扩展文件中:
import SpriteKit
extension EnvironmentElement {
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
if (touch.tapCount >= 2) {
NSObject.cancelPreviousPerformRequestsWithTarget(self)
}
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
if (touch.tapCount == 1) {
delegate.handleActionOnElement(self, actionType: ActionType.Single)
// Unable to find Swift equivalent to this: [self performSelector:@selector(onFlip) withObject:nil afterDelay:0.3];
} else {
delegate.handleActionOnElement(self, actionType: ActionType.Double)
}
}
}
}