0

When user clicks on a pin, the MKAnnotationView comes up, but it is very limited. I created a custom button but is there a way to customize the entire view that comes up from the pin? Here is what I have so far.

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {


    let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "location")
    annotationView.canShowCallout = true

    let btn = UIButton(type: .Custom) as UIButton
    btn.frame = CGRectMake(50, 60, 60, 50)
    btn.setTitle("button", forState: .Normal)
    btn.titleLabel?.textAlignment = NSTextAlignment.Center
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center

    btn.layer.borderColor = UIColor.blueColor().CGColor
    btn.layer.borderWidth = 0.5

    btn.backgroundColor = UIColor.redColor()

    annotationView.rightCalloutAccessoryView = btn

    return annotationView
}
IvOS
  • 323
  • 3
  • 13
  • See `detailCalloutAccessoryView`, in which you can place whatever complex view you want. See http://stackoverflow.com/a/17772487/1271826. – Rob Feb 13 '16 at 17:31

1 Answers1

2

You should be able to programmatically construct your own UIViews and assign them to the leftCalloutAccessoryView, rightCalloutAccessoryView, and detailCalloutAccessoryView properties of the MKPinAnnotationView. UIButton is a subclass of UIView, so what you have so far should theoretically work.

If you stick with these 3 properties and play with the frame property for each UIView, you should be able to perform a decent amount of customization. Also keep in mind each UIView can have multiple subviews.

The "Hacky" Solution

If you really want to make a fully customizable callout, you probably need to set up a tap gesture recognizer on the pin itself, which would cause your custom callout view to appear. However, I would advise against this more "hacky" method as it will likely result in the callout being more glitchy. Unfortunately, I don't believe there's a way to directly assign a custom callout view.

Edit: As Rob suggested, you could implement didSelectAnnotationView in your MKMapViewDelegate to spawn your custom callout view instead of a tap gesture recognizer. This is a better but still "hacky" solution-- it would be more glitchy than the stock callout view.

BradzTech
  • 2,755
  • 1
  • 16
  • 21