简体   繁体   中英

UIPinchGestureRecognizer is firing twice

I am adding UIPinchGestureRecognizer to a scrollView which shows images. On pinch, I am presenting a new view.

var pinch = UIPinchGestureRecognizer(target: self, action: "showFullScreen:")
self.scrollView.addGestureRecognizer(pinch)

The showFullScreen function:

func showFullScreen(sender:UITapGestureRecognizer) {     
    presentViewController(photoBro, animated: true, completion: nil)
}

But when I pinch on scrollView, showFullScreen is called twice because of which the following error comes:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modally an active controller

I was searching for solution, and they suggest to remove the pinchGesture, but I want to keep the gestureRecognizer, so that users can still pinch to enter full screen.

What can I do to ensure that showFullScreen is called only once for one pinch?

try this:

  func showFullScreen(sender:UITapGestureRecognizer) {     
     if(sender.state == UIGestureRecognizerState.Ended) {
         presentViewController(photoBro, animated: true, completion: nil)
     }    
  }

If you don't specify which state you want to listen to simply calling a selector from a gesture will fire any/every state from the below list.

so try using for anyof these states

typedef enum {
   UIGestureRecognizerState.Possible,
   UIGestureRecognizerState.Began,
   UIGestureRecognizerState.Changed,
   UIGestureRecognizerState.Ended,
   UIGestureRecognizerState.Cancelled,
   UIGestureRecognizerState.Failed,
   UIGestureRecognizerState.Recognized = UIGestureRecognizerState.Ended
} UIGestureRecognizerState;

Your code is running twice for both statedBegan and for stateEnded states

func showFullScreen(sender:UITapGestureRecognizer) {     
         if (sender.state == UIGestureRecognizerState.Began) {

    }
    if (sender.state == UIGestureRecognizerState.Ended) {
       //your dismiss code here
    }

Unlike UITapGestureRecognizer and UISwipeGestureRecognizer , which are discrete, UIPinchGestureRecognizer is continuous.

This means that Tap and Swipe recognizers will send a message once they are done, but Pinch (and Pan) recognizers will continuously send messages as the gesture progresses, to allow you to use the recognizer to create an interaction.

Like it's been suggested, you can check the recognizer state to show the controller when it's ended, you can also add a flag to make sure the presentation is not called twice. This would give you more flexibility, like only presenting the controller if the pinch reaches a certain distance.

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