简体   繁体   中英

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM