如何在一个ViewController中保存当前位置坐标并传递给swift中的另一个ViewController?

时间:2018-04-23 13:18:39

标签: ios swift xcode

我目前正在学习swift,我想在一个View Controller(ViewController A)中找到用户的当前位置并保存。然后在另一个View Controller(ViewController B)中显示保存的位置。它可以找到并找到当前位置。打印时,它也会显示坐标。但它无法传递给另一个View Controller。我不确定它是否是保存坐标的合适方法(在函数中返回一个值)。以下是我使用的代码:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) -> CLLocation {   

      let currentLocation: CLLocation = locations[0] as CLLocation
      let lat = currentLocation.coordinate.latitude
      let long = currentLocation.coordinate.longitude
      let center = CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
      let latDelta = 0.05
      let longDelta = 0.05
      let currentLocationSpan:MKCoordinateSpan =
            MKCoordinateSpanMake(latDelta, longDelta)
      let region = MKCoordinateRegion(center: center, span: currentLocationSpan)

      myMapView.setRegion(region, animated: true)

      let myAnnotation: MKPointAnnotation = MKPointAnnotation()
      myAnnotation.coordinate = CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
      myAnnotation.title = "Current Location"
      myMapView.addAnnotation(myAnnotation)

      print("The latitude is \(lat)")
      print("The longitude is\(long)")
      print(currentLocation)

     return currentLocation 
 }

在View Controller B中,代码就是这样,它不知道currentLocation是什么:

class ViewControllerB: ViewControllerA {

   override func viewDidLoad() {

     super.viewDidLoad()

     let center = CLLocationCoordinate2D(latitude:currentLocation.coordinate.latitude, longitude:currentLocation.coordinate.longitude)
}

有谁知道如何修复它?数百万谢谢!

1 个答案:

答案 0 :(得分:0)

ViewControllerB上为CLLocation创建一个属性,并在适当的时间设置值(基于视图控制器的连接方式):

class ViewControllerB: ViewControllerA {

 let currentLocation: CLLocation? = nil

 override func viewDidLoad() {

    super.viewDidLoad()
    guard let currentLocation = currentLocation else { return }
    let center = CLLocationCoordinate2D(latitude:currentLocation.coordinate.latitude, longitude:currentLocation.coordinate.longitude)
}

然后,ViewControllerA

中的某个地方
viewControllerB.currentLocation = currentLocation