How to add button to MKPointAnnotation in Swift

后端 未结 1 2022
失恋的感觉
失恋的感觉 2020-12-19 21:18

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 appe

相关标签:
1条回答
  • 2020-12-19 21:40

    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:

    Hope that helps you!

    0 讨论(0)
提交回复
热议问题