我希望在第二个视图控制器上的两个标签中保存纬度和经度坐标,但我无法让它工作。
这是我的代码:
First View Controller:
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet var map: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0]
let latitude = userLocation.coordinate.latitude
let longitude = userLocation.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: location, span: span)
self.map.setRegion(region, animated: true)
}
}
第二视图控制器:
import UIKit
class AddSightingViewController: UIViewController {
var getCoordinates: ViewController!
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
latitudeLabel.text = "\(getCoordinates.locationManager.location?.coordinate.latitude)"
longitudeLabel.text = "\(getCoordinates.locationManager.location?.coordinate.longitude)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:0)
当你推VC时
objAddSightVC.location = CLLocationCoordinate2D(latitude: your_lat, longitude: your_long)
AddSightingViewController
中的
var location : CLLocationCoordinate2D!
和
latitudeLabel.text = String(describing: location.latitude)
longitudeLabel.text = String(describing: location.longitude)
答案 1 :(得分:0)
启动或推送VC
let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
let addSightingViewController = AddSightingViewController(location :coordinate)
使用init构造函数在AddSightingViewController中声明属性位置
class AddSightingViewController: UIViewController {
let location:LLocationCoordinate2D
init(location:LLocationCoordinate2D!){
self.location = location
}
override func viewDidLoad() {
super.viewDidLoad()
latitudeLabel.text = "\(location?.coordinate.latitude)"
longitudeLabel.text = "\(location?.coordinate.longitude)"
}
}