【问题标题】:How to add annotation to map from another View Controller如何添加注释以从另一个视图控制器映射
【发布时间】:2020-09-02 08:22:00
【问题描述】:

我想使用CreateDetailsViewController 中的按钮创建注释以将其添加到MapViewController

当我在 MapView 上的 viewDidLoad 中键入以下代码时,它可以正常工作。但我不知道如何从一个屏幕到另一个屏幕实现它。

我对编程很陌生,所以请在回答时考虑这一点。谢谢!


  //Button I want to create the annotation with in `CreateDetailsViewControllwer` :

 @IBAction func publishButtonPressed(_ sender: UIButton) {
        
        
        performSegue(withIdentifier: "goToMap", sender: self)
        
        func prepare (for segue: UIStoryboardSegue, sender: Any?) {
            
            let MapVC = segue.destination as! MapViewController
            
            var london = MKPointAnnotation()
            london.title = "London"
            london.coordinate = CLLocationCoordinate2DMake(51.508530, -0.076132)
            MapVC.mapView.addAnnotation(london)
            
            func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
                guard annotation is MKPointAnnotation else {return nil}
                
                let identifier = "Annotation"
                var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
                
                if annotationView == nil {
                    annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                    annotationView!.canShowCallout = true
                } else {
                    annotationView!.annotation = annotation
                }
                
                 return annotationView
                
            }

【问题讨论】:

    标签: ios swift xcode annotations mapkit


    【解决方案1】:

    嗨 Selen,您需要使用通知中心

    通知中心:您可以将数据从您的一个视图控制器广播到另一个。

     @IBAction func publishButtonPressed(_ sender: UIButton) {
    
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pin koy"), object: nil)
        
        performSegue(withIdentifier: "goToMap", sender: self)
       
    }
    

    然后在你想要创建注解的地方使用这段代码(我认为是mapViewController)

    override func viewDidLoad() {
         super.viewDidLoad()
    
    NotificationCenter.default.addObserver(self, selector: #selector(pinleme), name: NSNotification.Name(rawValue: "pin koy"), object: nil)
    }
    

    它是你注释的函数;

    @objc func pinleme() {
        let annotation= MKPointAnnotation()
    
        annotation.coordinate = CLLocationCoordinate2DMake(51.508530, -0.076132)
    
        annotation.title = "London"
        
        mapKit.addAnnotation(annotation)
    
        //anlamadıysan inst-fburakk19
    }
    

    【讨论】:

    • 谢谢布拉克!这为我节省了很多时间和精力。
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    相关资源
    最近更新 更多