swifter22
swifter22

Reputation: 65

How would I use the UILongPressGestureRecognizer in my App in Swift Spritekit?

I have a node in the middle of my screen and currently have this code that moves the node to the left with each tap on the left side of the screen and to the right with each tap on the right side of the screen. I want to change this to a long press instead of a tap. How would I do this? Thanks! This is the code for the tap.

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

Upvotes: 0

Views: 831

Answers (1)

ravron
ravron

Reputation: 11211

This should be very straightforward. Initialize a UILongPressGestureRecognizer in your view's initializer. You can optionally adjust the minimumPressDuration and allowableMovement properties if desired before adding the gesture recognizer to the view.

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)

    // ...
}

Then just implement the callback method:

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

Upvotes: 1

Related Questions