问题
As you can see I've created a new annotation right here
var pin = CustomPointAnnotation()
pin.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
pin.title = "Bus Stop"
pin.subtitle = "City Stand D"
pin.imageName = "pin"
mapView.addAnnotation(pin)
Now when a user clicks on the annotation, I want to run a method. But my question is:
How do I know which annotation they clicked on?
Then the problem is I am using a loop to create multiple annotations so I can't set the tag because it will just become the last set tag.
Then here I want to print a tag which can be set differently for each annotation
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
print(view.tag)
}
回答1:
As I can see, you've already created a class subclassing a MKPointAnnotation
.
This is simple, you just create a variable with a name and type.
class CustomPointAnnotation: MKPointAnnotation {
var tag: Int!
}
Then in your code, set the variable.
var pin = CustomPointAnnotation()
pin.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
pin.title = "Bus Stop"
pin.subtitle = "City Stand D"
pin.imageName = "pin"
pin.tag = index
mapView.addAnnotation(pin)
Then to access the variable when you click on the annotation. Simply do it here.
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let annotation = view.annotation as? CustomPointAnnotation {
print(annotation.tag!)
}
}
There you go.
If you have any issues shoot me a comment.
来源:https://stackoverflow.com/questions/51591670/how-to-identify-when-a-annotation-is-pressed-which-one-it-is