Swift从输入坐标添加引脚位置

时间:2016-12-18 02:40:53

标签: swift mkmapview

我提示用户从另一个视图控制器输入纬度和纵向坐标。我不确定如何将这些坐标转换为可以放置引脚的地图。下面是我的故事板的设置。

enter image description here

我应该使用UserDefaults传输保存的坐标还是全局变量?我不确定解决这个问题的最佳方法是什么。

1 个答案:

答案 0 :(得分:1)

通过设置其中一个属性,将参数从第一个视图控制器传递到第二个视图控制器。

这是一个循序渐进的指南:

1 - 在FirstViewController中,实施UITabBarControllerDelegate协议

class FirstViewController: UIViewController, UITabBarControllerDelegate {
    @IBOutlet weak var latitudeField: UITextField!
    @IBOutlet weak var longtitudeField: UITextField!

    var coordinates = [CLLocationCoordinate2D]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBarController?.delegate = self
    }

    @IBAction func addCoordinates(_ sender: Any) {
        guard let lat = Double(latitudeField.text!), let long = Double(longtitudeField.text!) else {
            return
        }

        self.coordinates.append(CLLocationCoordinate2D(latitude: lat, longitude: long))
    }

    // This method will be called whenever you are switching tab
    // Note that the viewController can be the same view controller, i.e. FirstViewController
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        guard let secondViewController = viewController as? SecondViewController else {
            return
        }
        secondViewController.coordinates = self.coordinates
    }
}

2 - 在SecondViewController显示坐标的引脚:

class SecondViewController: UIViewController, MKMapViewDelegate {
    @IBOutlet weak var mapView: MKMapView!

    var coordinates = [CLLocationCoordinate2D]() {
        didSet {
            // Update the pins
            // Since it doesn't check for which coordinates are new, it you go back to
            // the first view controller and add more coordinates, the old coordinates
            // will get a duplicate set of pins
            for (index, coordinate) in self.coordinates.enumerated() {
                let annotation = MKPointAnnotation()
                annotation.coordinate = coordinate
                annotation.title = "Location \(index)"

                mapView.addAnnotation(annotation)
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        let identifier = "pinAnnotation"
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView

        if annotationView == nil {
            annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            annotationView?.canShowCallout = true
        }

        annotationView?.annotation = annotation
        return annotationView
    }
}