无法将自来水手势添加到自定义标注视图

时间:2014-06-12 13:16:40

标签: ios objective-c

我的应用中有一个mapview,需要为每个地图注释定制calloutView。 因此,我有一个这个自定义calloutView的XIB文件。 这是我的地图视图控制器代码

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    CustomCalloutView *calloutView = (CustomCalloutView *)[[[NSBundle mainBundle] loadNibNamed:@"CustomCalloutView" owner:self options:nil] objectAtIndex:0];
    [calloutView.layer setCornerRadius:10];
    CGRect calloutViewFrame = calloutView.frame;
    calloutViewFrame.origin = CGPointMake(-calloutViewFrame.size.width/2 + 15, -calloutViewFrame.size.height);
    calloutView.frame = calloutViewFrame;

    // some other code such as load images for calloutView

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap)];
    singleTap.numberOfTapsRequired = 1;
    [calloutView addGestureRecognizer:singleTap];
    [view addSubview:calloutView];
}

- (void)handleSingleTap{
    NSLog(@"it works");
}

但是,handleSingleTap:从未被调用过。相反,calloutView上的每次点击都只会简单地关闭calloutView。我还尝试在calloutView上添加一个按钮,但点击它也会导致calloutView被解雇,而不是调用按钮动作。

有人可以帮忙吗?

更新

我试图更改代码

    [view addSubview:calloutView];

    [self.view addSubview:calloutView];

将自定义的calloutView添加到主容器视图而不是mapView中。

然后,它可以轻按手势。因此,我认为问题应该是由mapView引起的,似乎mapView将calloutView上的所有触摸事件传递给自己。有人有这方面的想法吗?

2 个答案:

答案 0 :(得分:1)

行。我终于找到了解决方案。我们需要为MKAnnotationView定制一个类来解决这个问题。这是.m文件中的代码

- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event
{
    UIView* hitView = [super hitTest:point withEvent:event];
    if (hitView != nil)
    {
        [self.superview bringSubviewToFront:self];
    }
    return hitView;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
    CGRect rect = self.bounds;
    BOOL isInside = CGRectContainsPoint(rect, point);
    if(!isInside)
    {
        for (UIView *view in self.subviews)
        {
            isInside = CGRectContainsPoint(view.frame, point);
            if(isInside)
                break;
        }
    }
    return isInside;
}

希望这对其他人有用。

答案 1 :(得分:0)

您需要修改自来水手势实施&这个方法叫做了。看看&检查它是否有效。

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap)];
singleTap.numberOfTapsRequired = 1;
[calloutView addGestureRecognizer:singleTap];
[view addSubview:calloutView];


- (void)handleSingleTap:(UIGestureRecognizer *)recognizer {
    NSLog(@"it works");
}