如何识别Swift中是否按下了MKPointAnnotation?

How to identify if MKPointAnnotation has been pressed in Swift?

使用 for loop 我使用在名为 CustomPointAnnotation 的 class 中创建的标记在每个注释中存储了唯一的 URL。我正在尝试打印出已按下的注释的 URL 。 问题是我在 Xcode 中的输出控制台在我单击注释时不打印任何内容。

我试着遵循这个指南:

我复制了所有代码,但它没有检测注释是否被单击。

How do I know if the annotation is clicked?

这是 CustomPointAnnotation。

class CustomPointAnnotation: MKPointAnnotation {
        var tag: String!
    }

我声明了变量标签,这样我就可以为每个注释存储一个唯一的变量。

我的ViewControllerclass:

在 ViewController class 中有一个 循环遍历我的 Firebase 数据库 JSON 文件:

func displayCordinates() {
    ref = Database.database().reference()
    let storageRef = ref.child("waterfountains")

    storageRef.observeSingleEvent(of: .value, with: { snapshot in
        for child in snapshot.children.allObjects as! [DataSnapshot] {
            let annotation = CustomPointAnnotation()
            let dict = child.value as? [String : AnyObject] ?? [:]
            annotation.title = "Water Fountain"
            annotation.tag = dict["url"] as? String
            annotation.coordinate = CLLocationCoordinate2D(latitude: dict["lat"] as! Double, longitude: dict["long"] as! Double)
            self.mapView.addAnnotation(annotation)
            }
    })
}

通过调用viewDidLoad中的函数显示注解:

override func viewDidLoad() {
    super.viewDidLoad()

    displayCordinates()
}

检测注释是否被点击的函数:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let annotation = view.annotation as? CustomPointAnnotation {
        print(annotation.tag!)
    }  
}

感谢您的帮助。

mapView:didSelect: 是一种 MKMapViewDelegate 方法。如果您没有在 ViewController 上设置 mapView.delegate = self,则永远不会触发此功能。

通常会在 ViewDidLoad 中设置。在使用 mapView 执行任何其他操作之前。将您的 ViewDidLoad 更改为

override func viewDidLoad() {
    super.viewDidLoad()

    self.mapView.delegate = self
    displayCordinates()
}

应该可以解决您的问题。有关 apple 框架中 protocol/delegate 设计模式的更多信息,我建议 this swift article from the Swift Programming Guide.

更具体地针对您的情况,通过查看 [=23] 上的苹果文档,查看所有其他 functionality/control 您可以在 ViewController 上实现 MKMapView =].这将涵盖诸如监控地图何时完成加载、何时失败、何时更新用户位置等内容,以及您可能希望增加应用程序功能并提供出色用户体验的更多内容。