Swift 如何将经度和纬度变量传递给另一个函数?
我有“locationManager”功能,可以在其中创建和设置经度和纬度。我想做的是当按下按钮时能够得到那个位置。当我按下该按钮时,如何将经度和纬度输入@iAction?谢谢你的帮助Swift 如何将经度和纬度变量传递给另一个函数?,swift,xcode,function,Swift,Xcode,Function,我有“locationManager”功能,可以在其中创建和设置经度和纬度。我想做的是当按下按钮时能够得到那个位置。当我按下该按钮时,如何将经度和纬度输入@iAction?谢谢你的帮助 import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { let locationManager = CLLocationManager() ove
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
setupLocationManager()
}
func setupLocationManager() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
if location.horizontalAccuracy > 0 {
locationManager.stopUpdatingLocation()
let longitude = location.coordinate.longitude
let latitude = location.coordinate.latitude
print("longitude = \(longitude)")
print("latitude = \(latitude)")
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location update failed, \(error)")
}
@IBAction func buttonPressed(_ sender: UIButton) {
// print(longitude)
}
}
如果类的作用域为,则定义位置变量
fileprivate var mylocation:CLLocation?
设置我的位置
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
if location.horizontalAccuracy > 0 {
locationManager.stopUpdatingLocation()
myLocation = location
}
}
}
现在您可以在点击按钮时访问位置
@IBAction func buttonPressed(_ sender: UIButton) {
let longitude = myLocation.coordinate.longitude
let latitude = myLocation.coordinate.latitude
print("longitude = \(longitude)")
print("latitude = \(latitude)")
}
不评论代码的体系结构;每当调用locationManager()时,在print()语句所在的行中,为什么不将值存储到类变量中,以便在buttonPressed()中读取这些值?所以两个变量就在你的let locationManager=。。。