我无法将一些数据传递给另一个视图控制器。
我需要将注释的标题传递给我的第二个VC上的标签。
我不知道我到底哪里出错了,我整天都在摸不着头脑,试图解决它。
ViewController.swift
//Perform segue when callout has been tapped
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
self.performSegue(withIdentifier: "showAnnotationInfo", sender:view)
}
我目前正在尝试使用func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)
,但我收到的错误是:“在进行初始化之前使用”常量'destVC'。
在didSelect函数中,我能够在控制台中完美地显示所选的注释标题。
//Idenify when callout has been selected
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
print("Annotation selected")
if let annotation = view.annotation as? POIAnnotations {
let destVC : ShopDetailViewController?
//error: constant 'destVC' used before being initialized
destVC?.shopNameData = annotation.title!
print("Your annotation title is: \(annotation.title!)");
}
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showAnnotationInfo" {
//I'm not sure what goes here.
}
}
ShopDetailViewController.swift
一旦annotation.title传递给shopNameData,它就会传递给标签,如下所示。
var shopNameData = "thisDataMustChange"
override func viewDidLoad() {
super.viewDidLoad()
self.shopName.text = self.shopNameData
// Do any additional setup after loading the view.
}
答案 0 :(得分:2)
改为在prepareForSegue中设置shopNameData
。
if segue.identifier == "showAnnotationInfo" {
guard let annotationTitle = annotationTitle else {
print("annotation title not set before segue to ShopDetailViewController.")
return
}
guard let controller = segue.destination as? ShopDetailViewController else {
print("improper controller for this segue")
return
}
controller.shopNameData = annotationTitle
}
在地图上选择时设置annotationTitle
的位置。见下文。
var annotationTitle = ""
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let annotation = view.annotation as? POIAnnotations {
annotationTitle = annotation.title!
}
}
答案 1 :(得分:0)
在SE上尝试一些类似的问题,我得出了这样的结论:
var annotationTitle = ""
func mapView(_ mapView: MGLMapView, annotation: MGLAnnotation, calloutAccessoryControlTapped control: UIControl) {
// mapView.deselectAnnotation(annotation, animated: true) // Hide the callout view.
annotationTitle = annotation.title!!
performSegue(withIdentifier: "toDetail", sender: view)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "toDetail" ) {
print("Segue toDetail")
let annotationTitle = self.annotationTitle
let theDestination = segue.destination as! StationController
theDestination.LabelText = annotationTitle
}
}