iOS开发--MKMapView添加UIPanGestureRecognizer
来源:程序员人生 发布时间:2015-02-10 08:17:44 阅读次数:5336次
当我们想给MKMapView添加拖动手势时,第1个想法多是这样:
- (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");
}
对照1下前后两段程序,后1段程序对手势辨认的代理进行了赋值,并实现了shouldRecognizeSimultaneouslyWithGestureRecognizer代理方法。
分析1下第2段代码运行成功的缘由:MKMapView内部实现时,已添加了1个UIPanGestureRecognizer,而这里我们又添加了另外1个UIPanGestureRecognizer,也就是说同1个MKMapView有两个相同类型的手势辨认,但是运行时内部默许相同类型的手势辨认只有1个会得到处理,所以第1段代码始终没有输出handlePan。幸亏UIPanGestureRecognizerDelegate提供了gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer方法,该方法返回YES时,意味着所有相同类型的手势辨认都会得到处理。
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠