如何将注释的标题和描述数据传递给另一个 ViewController

How to pass title and description data of an annotation to another ViewController

我想从 MapViewController 中选定的注释向我的 DetailsViewController 传递数据。

我正在尝试使用下面的代码保留所选注释的数据。 我还添加了一个 prepare for segue 方法。

我正在从 Firebase 检索数据,因此每个注释都有不同的标题和描述。

titleLabeldescriptionLabel 不会在 DetailsViewController 上显示文本。

我是编程新手,非常感谢任何帮助! 如果我需要提供任何其他信息,请告诉我。


    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    
    var selectedAnnotation = view.annotation
    
    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        if (segue.identifier == "goToDetails") {
           
        let detailsVC = segue.destination as! DetailsViewController
            
            detailsVC.TitleLabel.text = selectedAnnotation?.title as! String
            detailsVC.DescriptionLabel.text = selectedAnnotation?.subtitle as! String
        }
        
    }
    
    self.performSegue(withIdentifier: "goToDetails", sender: nil)
    
    
   }
  1. 在 DetailsViewController 中创建两个字符串变量。

    var detailTitle = ""
    
    var detailDescription = ""
    
  2. 在您的第一个控制器中执行此操作:

    var selectedTitle = ""
    
    var selectedDescription = ""
    
    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
       if segue.identifier == "goToDetails" {
          let detailsVC = segue.destination as! DetailsViewController
          detailsVC.detailTitle = selectedTitle
          detailsVC.detailDescription = selectedDescription
       }
    }
    
    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    
       if let selectedAnnotation = view.annotation {
    
          if let title = selectedAnnotation.title {
            self.selectedTitle = title
          }
    
          if subtitle = selectedAnnotation.subtitle {
            self.selectedDescription = subtitle
          } 
       }
    
       self.performSegue(withIdentifier: "goToDetails", sender: nil)
    }
    
  3. 问题是,您正在尝试设置没有标签的文本 created.In 您的第二个 viewcontroller (DetailsViewController) 执行此操作,因此创建了标签,您可以给他们你的短信

     override func viewDidLoad() {
        super.viewDidLoad()
        self.titleLabel.text = detailTitle
        self.descriptionLabel.text = detailDescription
     }