Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

ios - 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!)
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...