xcode 用户驾驶汽车时,速度标签值不变

8ulbf1ek  于 2023-01-31  发布在  其他
关注(0)|答案(2)|浏览(173)

我是Swift的新手,我已经实现了Google Maps SDK,我也想显示用户开始移动或驾驶汽车时的速度。
我正在使用CLLocationSpeed并将其存储在变量中。
现在,我得到的速度值时,用户点击开始按钮导航,但它不会改变用户移动。我想使它更动态。
我已附上代码和图像的标签相同:

var locationManager: CLLocationManager
 var speedlabel: UILabel = UILabel()
 var timerspeed: Timer?
 var speed: CLLocationSpeed = CLLocationSpeed()

@objc func runspeedcheck() {
        speedlabel.text = "\(speed)kph"
        
    }

func startnavigation {

 timerspeed = Timer(timeInterval: 1.0, target: self, selector: #selector(runspeedcheck), userInfo: nil, repeats: true)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        speed = locationManager.location!.speed
}

使它更动态化是正确的方法吗?或者有什么方法可以随着用户的移动而改变速度标签吗?

00jrzges

00jrzges1#

无需创建单独的CLLocationSpeed变量来获取speed更新。
你可以简单地这样做,

class VC: UIViewController, CLLocationManagerDelegate {
    @IBOutlet weak var speedlabel: UILabel!
    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let speed = manager.location?.speed {
            self.speedlabel.text = String(describing: speed)
        }
    }
}

以上是示例代码,请根据您的需要进行修改。

fdbelqdn

fdbelqdn2#

func getUserSpeed() {
     var speed: CLLocationSpeed = CLLocationSpeed()
     guard let userSpeed = locationManager.location?.speed else { return }
     speed = userSpeed
     if speed < 0 { speed = 0 }
    speedLabel.text = String(format: "%.0f km/h", speed * 3.6)
   }

相关问题