MKAnnotationView和点击检测 [英] MKAnnotationView and tap detection

查看:347
本文介绍了MKAnnotationView和点击检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 MKMapView 。我只需点按一下即可添加 UITapGestureRecognizer

I have a MKMapView. I added a UITapGestureRecognizer with a single tap.

我现在要添加 MKAnnotationView 到地图。我可以点击注释和 mapView:mapView didSelectAnnotationView:view fires(这是我将添加额外逻辑以显示UIView的地方)。

I now want to add a MKAnnotationView to the map. I can tap the annotation and mapView:mapView didSelectAnnotationView:view fires (which is where I'll add additional logic to display a UIView).

问题是,当我点击注释时, MKMapView 点击手势也会触发。

The issue is now when I tap the annotation, the MKMapView tap gesture also fires.

我可以设置它,如果我点击注释,它只响应吗?

Can I set it so if I tap the annotation, it only responds?

推荐答案

可能有更好更清洁的解决方案但一种方法是在挖掘手势识别选择器中利用 hitTest:withEvent:,例如

There might be a better and cleaner solution but one way to do the trick is exploiting hitTest:withEvent: in the tap gesture recognized selector, e.g.

假设您已为 _mapView

- (void)tapped:(UITapGestureRecognizer *)g
{
    CGPoint p = [g locationInView:_mapView];
    UIView *v = [_mapView hitTest:p withEvent:nil];

    if (v ==  subviewOfKindOfClass(_mapView, @"MKAnnotationContainerView"))
        NSLog(@"tap on the map"); //put your action here
}

// depth-first search
UIView *subviewOfKindOfClass(UIView *view, NSString *className)
{
    static UIView *resultView = nil;

    if ([view isKindOfClass:NSClassFromString(className)])
        return view;

    for (UIView *subv in [view subviews]) {
        if ((resultView = subviewOfKindOfClass(subv, className)) break;
    }
    return resultView;
}

它可能并未涵盖所有边缘情况,但它似乎工作漂亮对我好。

It's probably doesn't cover all the edge cases but it seems to work pretty well for me.

UPDATE(iOS> = 6.0)

最后,我找到了另一种解决方案,它的缺点是只对 iOS> = 6.0 有效:事实上,这个解决方案利用了新的 - (BOOL)gestureRecognizerShouldBegin :( UIGestureRecognizer * )gestureRecognizer 以这种方式添加到 UIView

Finally, I found another kind of solution which has the drawback of being valid only for iOS >= 6.0: In fact, this solution exploits the new -(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer added to the UIViews in this way

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    // overrides the default value (YES) to have gestureRecognizer ignore the view
    return NO; 
}

即从iOS 6开始,覆盖 UIVie就足够了w 手势识别器应忽略的每个视图中的方法。

I.e., from the iOS 6 onward, it's sufficient to override that UIView method in each view the gesture recognizer should ignore.

这篇关于MKAnnotationView和点击检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆