【问题标题】:How to identify if MKPointAnnotation has been pressed in Swift?如何识别 MKPointAnnotation 是否已在 Swift 中按下?
【发布时间】:2019-06-29 02:25:40
【问题描述】:

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

我尝试遵循本指南:How to identify when an annotation is pressed which one it is

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

如何知道注释是否被点击?

这是 CustomPointAnnotation。

class CustomPointAnnotation: MKPointAnnotation {
        var tag: String!
    }

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

我的ViewController班级:

在 ViewController 类中有一个循环遍历我的 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 执行任何其他操作之前。欢迎使用 Stack Overflow!
  • self.mapView.delegate = self;在视图控制器 viewWillAppear 方法中尝试此操作,希望有所帮助。
  • @NSGangster 非常感谢它的工作!

标签: ios swift mapkit mkannotation mkannotationview


【解决方案1】:

mapView:didSelect: 是一个MKMapViewDelegate 方法。如果你没有在你的ViewController 上设置mapView.delegate = self,这个函数将永远不会被触发。

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

override func viewDidLoad() {
    super.viewDidLoad()

    self.mapView.delegate = self
    displayCordinates()
}

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

更具体地说,通过查看MKMapViewDelegate 上的苹果文档,查看您的ViewController 上的MKMapView 实现可以带来的所有其他功能/控制。这将涵盖诸如监控地图何时完成加载、何时失败、何时更新用户位置,以及您可能希望增加应用功能并提供出色用户体验的更多内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多