How to identify when a annotation is pressed which one it is

这一生的挚爱 提交于 2020-01-15 05:13:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!