iosswiftuibuttonannotationsmkmapview

How to add button to MKPointAnnotation in Swift


I want to be able to put a button and label on my map annotation. The annotation with the title, subtitle, and coordinates works perfectly, but I can't get a button to appear.

func drawEvents(_ loc: CLLocation, title1: String)
    {
        mapView.delegate = self//
        let center = CLLocationCoordinate2D(latitude: loc.coordinate.latitude, longitude: loc.coordinate.longitude)
        let lat: CLLocationDegrees = center.latitude
        let long: CLLocationDegrees = center.longitude
        self.pointAnnotation1 = MKPointAnnotation()
        self.pointAnnotation1.title = title1
        self.pointAnnotation1.subtitle = "Event"
        self.pointAnnotation1.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
        self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation1, reuseIdentifier: nil)
        self.mapView.addAnnotation(self.pinAnnotationView.annotation!)
    }

Solution

  • This can be accomplished by adding a UIButton to the rightCalloutAccessoryView of the MKPinAnnotationView. Here is an example:

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if !(annotation is MKUserLocation) {
            let pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: String(annotation.hash))
    
            let rightButton = UIButton(type: .contactAdd)
            rightButton.tag = annotation.hash
    
            pinView.animatesDrop = true
            pinView.canShowCallout = true
            pinView.rightCalloutAccessoryView = rightButton
    
            return pinView
        }
        else {
            return nil
        }
    }
    

    This is what that'll look like:

    Annotation View Button

    Hope that helps you!