我想显示annotationview
的callout
始终显示,我的意思是当加载mapview
时,会显示所有注释的callout
。
我该怎么做?
在任何时候,地图上都只能有一个标注。当要显示新的标注时,框架会重复使用以前的标注,当添加注释时,这里显示一个标注视图,就像一样
let annotation = MKPointAnnotation()
annotation.title = "Title for Callout"
mapView.addAnnotation(annotation)
这导致委托方法viewForAnnotation
被激发:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let view = MKAnnotationView(annotation: annotation, reuseIdentifier: "AnnotId")
view.canShowCallout = true
return view
}
框架将添加上面返回的视图,并且didAddViews
委托被激发,现在通过选择注释来显示调出视图,就像一样
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
if let annotation = views.first(where: { $0.reuseIdentifier == "AnnotId" })?.annotation {
mapView.selectAnnotation(annotation, animated: true)
}
}
- 在地图上添加注释:
mapView.addAnnotation(myAnnotation)
- 选择注释
mapView.selectAnnotation(myAnnotation, animated: false)
- 添加私有函数
private func bringMyAnnotationToFront()
,代码为if let myAnnotation = mapView.annotations.first(where: { $0 is MKPointAnnotation }) { mapview.selectAnnotation(myAnnotation, animated: false) }
- 设置MKMapViewDelegate并使用
bringMyAnnotationToFront
实现两种方法:func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)
、func mapView(MKMapView, didDeselect: MKAnnotationView)