我试图让标注工作,但那没有发生,因为我在准备 segue 时做错了什么。我想知道如何能够对另一个 View 进行引脚注释标注?
最佳答案
当调用中的按钮被点击时,转到另一个场景的过程是这样的:
将 map View 的
委托(delegate)
设置为 View Controller 。您可以在 Interface Builder 的“Connections Inspector”中或以编程方式执行此操作。您还想指定 View Controller 也符合MKMapViewDelegate
。创建注释时,请确保也设置标题:
let annotation = MKPointAnnotation() annotation.coordinate = coordinate annotation.title = ... mapView.addAnnotation(annotation)
定义一个带按钮标注的注释 View 子类:
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
使用此注释 View 。 iOS 11 简化了这个过程,但我将描述如何以两种方式进行:如果您的最低 iOS 版本是 11(或更高版本),您只需将自定义注释 View 注册为默认 View 即可。在 iOS 11 及更高版本中,您通常根本不会实现
mapView(_:viewFor:)
。 (您唯一可以实现该方法的情况是,如果您需要注册多个重用标识符,因为您有多种类型的自定义注释类型。)override func viewDidLoad() { super.viewDidLoad() mapView.register(CustomAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier) }
如果您需要支持 iOS 11 之前的版本,请确保将您的 View Controller 指定为
MKMapView
的委托(delegate),然后实现mapView(_:查看方式:)
: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
按钮:实现以编程方式执行 segue 的
calloutAccessoryControlTapped
:func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { performSegue(withIdentifier: "SegueToSecondViewController", sender: view) }
显然,这假设您已经在两个 View Controller 之间定义了一个 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 } }
有关详细信息,请参阅 Creating Callouts在位置和 map 编程指南中。
有关上述内容的 Swift 2 实现,请参阅 previous revision of this answer .
关于ios - 如何在 Swift 中制作引脚注释标注?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33978455/