标签:
当我们想给MKMapView添加拖动手势时,第一个想法可能是这样:
- (void)viewDidLoad { //.... UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]; [self.mapView addGestureRecognizer:panGesture]; } - (void)handlePan:(UIPanGestureRecognizer*) recognizer { NSLog("handlePan"); }运行程序,然后拖动地图,我们会发现,控制台并没有打印任何的“handlePan”,也就是说手势识别处理函数handlePan从来没有被执行。后来在stackoverflow上找到了答案,正确的解决方法如下:
- (void)viewDidLoad { //...... UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]; panGesture.delegate = self; [self.mapView addGestureRecognizer:panGesture]; } - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES; } - (void)handlePan:(UIPanGestureRecognizer*) recognizer { NSLog("handlePan"); }
对比一下前后两段程序,后一段程序对手势识别的代理进行了赋值,并实现了shouldRecognizeSimultaneouslyWithGestureRecognizer代理方法。
分析一下第二段代码运行成功的原因:MKMapView内部实现时,已经添加了一个UIPanGestureRecognizer,而这里我们又添加了另外一个UIPanGestureRecognizer,也就是说同一个MKMapView有两个相同类型的手势识别,然而运行时内部默认相同类型的手势识别只有一个会得到处理,所以第一段代码始终没有输出handlePan。幸好UIPanGestureRecognizerDelegate提供了gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer方法,该方法返回YES时,意味着所有相同类型的手势识别都会得到处理。
iOS开发--MKMapView添加UIPanGestureRecognizer
标签:
原文地址:http://blog.csdn.net/wang_lichun/article/details/42952891