ios - 如何在一个ViewController中保存当前位置坐标并快速传递给另一个ViewController?

标签 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)
}

有人知道怎么解决吗?数以百万计的感谢!

最佳答案

ViewControllerB 上为 CLLocation 创建一个属性,并在适当的时间设置该值(基于 View Controller 的连接方式):

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

关于ios - 如何在一个ViewController中保存当前位置坐标并快速传递给另一个ViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49982165/

相关文章:

ios - didDiscoverPeripheral : not working sometimes on background

ios - 访问 Realms 对象列表时出错 : Realm accessed from incorrect thread

ios - 如何在 Swift 4 中从自定义类导航到 UIViewController

c++ - 如何在 Xcode 中将图像添加到 C++ 项目

ios - 无法确定弹出箭头方向

ios - 如何获取流字节并转换回图像 - IOS

ios - 限制 UISwipeGestureRecognizer 区域

ios - 更新启动时调用的 View Controller

ios - 在 iOS 中使用 Twilio 发送短信

ios - 在 Spritekit 中使用 UITableView