Swift SKSpriteNode:检测 Tap/DoubleTap/LongPress [英] Swift SKSpriteNode: Detect Tap / DoubleTap / LongPress

查看:25
本文介绍了Swift SKSpriteNode:检测 Tap/DoubleTap/LongPress的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建 SKSpriteNode 的子类,它可以检测用户交互(点击、双击并按住),然后服从委托.在我看来,这似乎是一个相对普遍的需求,但是:

I'm attempting to create a subclass of SKSpriteNode which can detect user interaction (tap, double tap and hold), then defer to a delegate. This seems to me like a relatively common need, but:

  1. 该代码无法检测双击而不触发单击.
  2. 我根本没有找到检测按住/长按操作的方法.

我的意思是不是全错了?我不禁觉得 SpriteKit 应该有一些标准来处理如此基本的事情.我知道有 UIGestureRecognizer,但它似乎与特定的 SKNodes 而不是 UIViews 不太兼容.

Am I going about this all wrong? I can't help feeling that SpriteKit should have something standard to handle something so basic. I know there's UIGestureRecognizer, but it doesn't seem very compatible with specific SKNodes rather than UIViews.

这是我目前拥有的.根据 Apple 的示例,我在主类文件中有所有非特定于设备的代码:

Here's what I have currently. Based on examples from Apple, I have all of the non-device-specific code in the main class file:

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 的代码:

...then all of the iOS-specific code in a separate extension file:

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)
            }
        }
    }
}

推荐答案

你可以在 touchesBegan:

这篇关于Swift SKSpriteNode:检测 Tap/DoubleTap/LongPress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆