UIPanGestureRecognizer on MKMapView?
Asked Answered
C

2

41

I would like to add some logic when user moves with map view i. e. he does a pan touch. But when I add the gesture recognizer and I want to log the touch, nothing happens. When I try it in another view controller and add the recognizer to controller's view then it works ok.

Here's my code (map view is a property of application delegate because I need to do some other things with it even if it isn't visible):

- (void)viewDidLoad
{
    ...
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(showPan)];
    [appDelegate.mapView addGestureRecognizer:panGesture];
    [panGesture release];
}

- (void)showPan
{
    NSLog(@"pan!");
}

I use latest iOS 4.2.1

Thanks for any advice.

Col answered 15/2, 2011 at 15:26 Comment(0)
C
144

Ok, because no one knew, I had to spent one Apple technical support consult for it. ;o)

Because MKMapView evidently has its own recognizers to interact with user, you have to adhere to the UIGestureRecognizerDelegate protocol and implement (BOOL)gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: like this:

- (void)viewDidLoad
{
    ...
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(showPan)];
    panGesture.delegate = self;
    [appDelegate.mapView addGestureRecognizer:panGesture];
    [panGesture release];
}

- (void)showPan
{
    NSLog(@"pan!");
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {   
    return YES;
}

Then it works like a charm.

Col answered 23/2, 2011 at 10:21 Comment(3)
Good Lord - thanks, that would have taken me a while to figure out!Georg
Important to mention that you can still define the gesture recogniser from the UIBuilder. So technically the important thing is the delegate method (you can ctrl-drag a recognizer from the builder to showPan, if you define it as an IBAction)Sherellsherer
Have you found a solution to the decelleration? When you're in mid scroll and you release, the map keeps going and slows down. I can't find a way to capture that.Acceptant
C
2

Swift 5

let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGesture))
panGesture.delegate = self
self.mapView.addGestureRecognizer(panGesture)

@objc func panGesture (sender: UIPanGestureRecognizer) {
        
}
    
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
   return true
}

Corset answered 30/11, 2021 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.