我目前正在学习 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/