How to handle taps on a custom callout view?

非 Y 不嫁゛ 提交于 2019-11-29 07:55:44
AdamPro13

It's because your annotation view only detects touches inside its bounds. Since your callout view extends beyond the bounds, the subview doesn't recognize the tap. You need to override the pointInside:withEvent: method in the annotation view so your callout will actually detect the touch.

Here's an example in 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;
}

EDIT:

Swift version:

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

Swift 4.0

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let rect = self.bounds;
    var isInside: Bool = rect.contains(point);
    if(!isInside)
    {
        for view in self.subviews
        {
            isInside = view.frame.contains(point);
            if isInside
            {
                break;
            }
        }
    }
    return isInside;
}
 override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
    let hitView = super.hitTest(point, with: event)
    if (hitView != nil)
    {
        self.superview?.bringSubview(toFront: self)
    }
    return hitView
}

Removing from annotation view swift 5

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let hitView = super.hitTest(point, with: event)
        if (hitView != nil)
        {
            self.superview?.bringSubviewToFront(self)
        }
        return hitView
    }
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let rect = self.bounds;
        var isInside: Bool = rect.contains(point);
        if(!isInside)
        {
            for view in self.subviews
            {
                isInside = view.frame.contains(point);
                if isInside
                {
                    break;
                }
            }
        }
        return isInside;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!