【发布时间】: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