我试图让标注工作,但这并没有发生,因为我在为 segue 做准备时做错了。我想知道如何能够对另一个视图进行引脚注释标注?
1 回答
当点击标注中的按钮时,切换到另一个场景的过程是这样的:
将
delegate
地图视图的设置为视图控制器。您可以在 Interface Builder 的“Connections Inspector”中或以编程方式执行此操作。您还想指定视图控制器MKMapViewDelegate
也符合 。创建注释时,请确保也设置标题:
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。
转场时,将必要的信息传递给目标场景。例如,您可以传递对注解的引用:
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 } }
有关更多信息,请参阅位置和地图编程指南中的创建标注。
对于上述的 Swift 2 实现,请参阅此答案的先前版本。