【问题标题】:Speed label value not changing as user drives car速度标签值不会随着用户驾驶汽车而改变
【发布时间】:2020-06-10 00:10:19
【问题描述】:

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

是让它更加动态的正确方法,还是有什么方法可以在用户移动时更改速度标签 任何帮助表示赞赏!

感谢和问候

【问题讨论】:

  • timerspeed的声明在哪里?
  • 它在速度标签下面..
  • 看看我的回答。

标签: swift xcode cllocationmanager gmsmapview


【解决方案1】:

无需创建单独的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)
        }
    }
}

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

【讨论】:

  • 会一直刷新吗??随着用户的移动?还是会保持静止??
  • 您好,我尝试了您的代码示例,但是当我单击退出按钮并再次启动导航时,但标签未显示,这意味着速度 var 设置为 nil
  • 你为什么要首先创建速度变量?
【解决方案2】:
   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)
   }

【讨论】:

  • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多