如何在Swift Spritekit中的应用程序中使用UILongPressGestureRecognizer?

时间:2015-03-14 13:24:46

标签: xcode swift

我的屏幕中间有一个节点,当前有这个代码可以将节点向左移动,每次点按屏幕左侧,右侧每次点按屏幕右侧。我想把它改成长按而不是点击。我该怎么做?谢谢!这是点击的代码。

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    var touch: UITouch = touches.anyObject() as UITouch
    var location = touch.locationInNode(self)
    var node = self.nodeAtPoint(location)

    var speedOfTouch:CGFloat = 30


    //moves to the left and right by touch and plays sound effect by touch.
    for touch: AnyObject in touches {

        let location = touch.locationInNode(self)
        if location.x < CGRectGetMidX(self.frame) {
            hero.position.x -= speedOfTouch
            AudioPlayer.play()
        } else {
            hero.position.x += speedOfTouch
            AudioPlayer.play()
        }

1 个答案:

答案 0 :(得分:1)

这应该非常简单。在视图的初始值设定项中初始化UILongPressGestureRecognizer。如果需要,您可以选择调整minimumPressDurationallowableMovement属性,然后再将手势识别器添加到视图中。

override init(frame aRect: CGRect) {
    // ...

    // Create the long press gesture recognizer, and configure it
    // to call a method named viewLongPressed: on self
    let longPress = UILongPressGestureRecognizer(target: self, action: "viewLongPressed:")

    // Optionally configure it - see the documentation for explanations
    // longPress.minimumPressDuration = 1.0
    // longPress.allowableMovement = 15

    // Add the gesture recognizer to this view (self)
    addGestureRecognizer(longPress)

    // ...
}

然后只需实现回调方法:

func viewLongPressed(gestureRecognizer: UIGestureRecognizer) {
    // Handle the long press event by examining the passed in
    // gesture recognizer
}