How to handle taps on a custom callout view?

前端 未结 3 1780
Happy的楠姐
Happy的楠姐 2020-12-18 06:08

I am adding a callout view like this:

func mapView(mapView: MKMapView!,
        didSelectAnnotationView view: MKAnnotationView!) {
    let calloutView = UIVi         


        
3条回答
  •  遥遥无期
    2020-12-18 06:41

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

提交回复
热议问题