【问题标题】:How can I get Swift to continuously update the speed如何让 Swift 不断更新速度
【发布时间】:2017-05-14 05:08:19
【问题描述】:

我一直在学习使用 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)"
    }


}

【问题讨论】:

    标签: swift cllocationmanager cllocation


    【解决方案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(),因此您可以删除一次调用

    【讨论】:

      猜你喜欢
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 2011-07-12
      • 1970-01-01
      相关资源
      最近更新 更多