在 Swift 中,我如何在按下按钮时将用户的位置存储在变量中?

In Swift, how can I store the user's location inside a variable when I press a button?

在主要 UIViewController 中,我想在用户按下 UIButton 时将用户的坐标存储在变量中。此变量将在另一个 UIViewController 中使用 MapView.

我尝试设置一个 locationManager(),但我无法让按钮使用它。有人可以帮忙吗?

下面是对您有帮助的代码:

var location: CLLocation! //to store location
lazy var locationManager: CLLocationManager = {
    let _locationManager = CLLocationManager()
    _locationManager.requestWhenInUseAuthorization()
    // adjsut _locationManager
    return _locationManager
}()

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.startUpdatingLocation()
}

@IBAction func buttonDidClick(sender: AnyObject) { //event handler
    location = locationManager.location //set current location
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "MyViewControllerSegue" { //before showing controller
        let dvc = segue.destinationViewController as! ViewController
        dvc.location = location //set the current location
    }
}