我一直在学习使用swift制作应用程序,并希望制作一个基本的应用程序,告诉你你的速度。但是我无法弄清楚如何让它更新速度,此刻它只给我初始速度并且永远不会用当前速度更新标签。这是我到目前为止的代码:
@IBOutlet var speedLabel: UILabel!
@IBOutlet var countLabel: UILabel!
let locationManager = CLLocationManager()
var speed: CLLocationSpeed = CLLocationSpeed()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
locationManager.startUpdatingLocation()
speed = locationManager.location!.speed
if speed < 0 {
speedLabel.text = "No movement registered"
}
else {
speedLabel.text = "\(speed)"
}
}
答案 0 :(得分:1)
使用委托方法https://developer.apple.com/reference/corelocation/cllocationmanagerdelegate
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
guard let speed = manager.location?.speed else { return }
speedLabel.text = speed < 0 ? "No movement registered" : "\(speed)"
}
此外,您要拨打两次locationManager.startUpdatingLocation()
,这样您就可以删除一个电话