我正在尝试创建SKSpriteNode的子类,该子类可以检测用户交互(轻按、双击和长按),然后转交给委托。这似乎是一个相对常见的需求,但有以下问题:
这是我目前拥有的。基于Apple的示例,我将所有非设备特定代码放在主类文件中:
- 代码无法检测到双击而不触发单击。
- 我没有找到一种方法来检测长按/长按操作。
这是我目前拥有的。基于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)
}
}
}
}