码迷,mamicode.com
首页 > 移动开发 > 详细

iOS开发--MKMapView添加UIPanGestureRecognizer

时间:2015-01-22 01:46:54      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

    当我们想给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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!