我试图让标注工作,但没有发生,因为我在准备继续时做错了。我想知道如何能够对另一个视图进行引脚注释标注?
当点击标注中的按钮时,跳转到另一个场景的过程如下:
Set the delegate
地图视图作为视图控制器。您可以在 Interface Builder 的“连接检查器”中或以编程方式执行此操作。您想要指定视图控制器符合MKMapViewDelegate
, too.
-
创建注释时,请确保也设置标题:
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = ...
mapView.addAnnotation(annotation)
-
定义带有按钮标注的注释视图子类:
class CustomAnnotationView: MKPinAnnotationView { // or nowadays, you might use MKMarkerAnnotationView
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
canShowCallout = true
rightCalloutAccessoryView = UIButton(type: .infoLight)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
-
指导你的MKMapView
使用此注释视图。 iOS 11 简化了该过程,但我将介绍如何以两种方式完成此操作:
-
如果您的最低 iOS 版本是 11(或更高版本),您只需将自定义注释视图注册为默认值即可。你一般不实施mapView(_:viewFor:)
在 iOS 11 及更高版本中完全没有。 (您可能实现该方法的唯一时间是您需要注册多个重用标识符,因为您有多种类型的自定义注释类型。)
override func viewDidLoad() {
super.viewDidLoad()
mapView.register(CustomAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
}
-
如果您需要支持 11 之前的 iOS 版本,您需要确保将您的视图控制器指定为MKMapView
然后将实施mapView(_:viewFor:)
:
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation { return nil }
let reuseIdentifier = "..."
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)
if annotationView == nil {
annotationView = CustomAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
} else {
annotationView?.annotation = annotation
}
return annotationView
}
}
例如,这会产生如下所示的标注,其中包含.infoLight
右侧按钮:
-
实施calloutAccessoryControlTapped
以编程方式执行segue:
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
performSegue(withIdentifier: "SegueToSecondViewController", sender: view)
}
显然,这假设您已经在两个视图控制器之间定义了一个segue。
-
当你进行segue时,将必要的信息传递到目标场景。例如,您可以传递对注释的引用:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? SecondViewController,
let annotationView = sender as? MKPinAnnotationView {
destination.annotation = annotationView.annotation as? MKPointAnnotation
}
}
有关更多信息,请参阅创建标注 in the 位置和地图编程指南。
对于上述内容的 Swift 2 实现,请参阅此答案的先前修订版.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)