一尘不染

如何处理自定义标注视图上的水龙头?

swift

我正在添加这样的标注视图:

func mapView(mapView: MKMapView!,
        didSelectAnnotationView view: MKAnnotationView!) {
    let calloutView = UIView(frame:
        CGRect(x: 0, y: 0, width: 300, height: 120))

    calloutView.backgroundColor = UIColor.purpleColor()
    calloutView.center = CGPointMake(CGRectGetWidth(view.bounds) / 2.0, 0.0)
    calloutView.layer.anchorPoint = CGPointMake(0.5, 1.0)
    calloutView.layer.masksToBounds = false

    calloutView.userInteractionEnabled = true
    let calloutViewTapRecognizer = UITapGestureRecognizer(target: self,
        action: "onCalloutViewTap")
    calloutView.addGestureRecognizer(calloutViewTapRecognizer)

    view.addSubview(calloutView)
}

尽管我的onCalloutViewTap函数从未被调用过……但我很好奇理解原因并获得了一些可以处理与标注视图交互的东西。


阅读 371

收藏
2020-07-07

共1个答案

一尘不染

这是因为注释视图仅检测其边界内的触摸。由于您的标注视图超出了范围,因此子视图无法识别点击。您需要pointInside:withEvent:在注释视图中覆盖该方法,以便您的标注实际上可以检测到触摸。

这是Objective-C中的一个示例:

- (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;
}

编辑

迅捷版:

override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
    let rect = self.bounds
    var isInside = CGRectContainsPoint(rect, point)

    if (!isInside) {
        for subview in subviews {
            isInside = CGRectContainsPoint(subview.frame, point)

            if (isInside) {
                break
            }
        }
    }

    println(isInside)

    return isInside;
}
2020-07-07