iOS开发--MKMapView添加UIPanGestureRecognizer

    当我们想给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时,意味着所有相同类型的手势识别都会得到处理。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值