简体   繁体   中英

How to turn a MKPointAnnotation to a button?

Whenever a user taps on an MKPointAnnotation , I want him to be redirected to a specific view. My problem is how do I get the annotation to perform an action when tapped?

Here is my code:

for i in closestpharmacyname {
                var docref2 = db.collection("pharmacies").document(i)
                print("Pharmacy: ", i)
                docref2.getDocument(source: .cache) { (document, error) in
                    if var document  = document {
                        var pharmacylatitude = document.get("latitude") as! Double
                        var pharmacylongitude = document.get("longitude") as! Double
                        print(pharmacylatitude, pharmacylongitude)
                             
                        var pharmacyannotation = MKPointAnnotation()
                        pharmacyannotation.coordinate = CLLocationCoordinate2D(latitude: pharmacylatitude, longitude: pharmacylongitude)
                        pharmacyannotation.title = i
                    
                        self.MapView.addAnnotation(pharmacyannotation)
                    } else{
                        print("Document Does not exist")
                    }
                    
                }
            }

To do this, you need to add:

yourAnnotationView?.rightCalloutView = UIButton(type: UIButtonType.detailDisclosure)

into your mapView(_:viewFor:) function. This will change the looks of your annotation, but there will be a button on the side that you can press to do different tasks.The annotation will look something like this: 在此处输入图像描述

In order to handle these tasks, you also need to add a new function:

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
  //perform tasks here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM