首页 > 解决方案 > 打印到标签的距离

问题描述

现在我正在打印控制台内两个位置之间的距离,但是如何在标签内打印呢?

现在我正在尝试使用self.distanceLabel.text = distance但使用此代码我得到以下错误行:无法将“Double”类型的值分配给“String?”

完整代码:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let lastLocation = locations.last {

        let myLocation = CLLocation(latitude: lastLocation.coordinate.latitude, longitude: lastLocation.coordinate.longitude)

        let myBuddysLocation = CLLocation(latitude: 59.326354, longitude: 18.072310)

        let distance = myLocation.distance(from: myBuddysLocation) / 1000
        print(String(format: "The distance to the Job is %.01fkm", distance))
        self.distanceLabel.text = distance
    }
}

标签: iosswiftcllocationmanager

解决方案


您需要分配的格式化字符串不是distance类型double

self.distanceLabel.text =  String(format: "The distance to the Job is %.01fkm", distance)     

或者像这样,如果你不需要描述

self.distanceLabel.text = "\(distance)"

推荐阅读