【问题标题】:In Swift, how can I store the user's location inside a variable when I press a button?在 Swift 中,当我按下按钮时,如何将用户的位置存储在变量中?
【发布时间】:2015-07-20 13:48:23
【问题描述】:

在主UIViewController 中,当用户按下UIButton 时,我想将用户的坐标存储在一个变量中。此变量将用于另一个带有MapViewUIViewController

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

【问题讨论】:

标签: ios swift core-location


【解决方案1】:

以下代码可以帮助您:

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
    }
}

【讨论】:

  • 谢谢,我想我可能初始化错了。在 viewDidLoad() 内部我可以很好地引用 locationManager,但是我的按钮事件处理程序无法识别它。
  • 你的意思是事件处理程序根本不引发?
  • 当我在事件处理程序中引用 locationManager 时,它无法识别管理器。我将尝试按照您的说明进行初始化。谢谢你的意见:)
  • 我编辑了一些关于位置管理器初始化的代码,请看这个惰性初始化方法
  • 谢谢!我会处理这个,并标记这是正确的。顺便说一句,我真的很感激时间。我是开发新手,感谢您的帮助而不是责备:)
猜你喜欢
  • 2017-03-21
  • 1970-01-01
  • 1970-01-01
  • 2016-08-10
  • 2023-03-10
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 2017-06-16
相关资源
最近更新 更多