问题描述
这类似于,但是在这种情况下我得到的答案似乎不起作用。
This is similar to a question I asked yesterday but the answer I got doesn't seem to work in this case.
我从Core Location获得的海拔高度值为米。我希望以本地化的形式显示这些内容。例如,我现在的海拔高度是海拔1839米。这应该显示为6033英尺。我能用 MeasurementFormatter
做的最好是1.143英里。
I'm getting altitude values in meters from Core Location. I want to display these in a localized form. As an example, the altitude where I am right now is 1839m above sea level. This should be displayed as 6033 feet. The best I can do with MeasurementFormatter
is "1.143 mi".
let meters : Double = 1839
let metersMeasurement = Measurement(value: meters, unit: UnitLength.meters)
let measurementFormatter = MeasurementFormatter()
measurementFormatter.locale = Locale(identifier: "en_US")
let localizedString = measurementFormatter.string(from: metersMeasurement)
回答上一个问题的 .naturalScale
选项在这里没有帮助。我认为这是框架的限制,但我想知道现在是否有人有解决方法。
The .naturalScale
option that answered my previous question doesn't help here. I think this is a limitation of the framework, but I wonder if anyone has a workaround for now.
推荐答案
创建一个Double将您的仪表单位转换为英尺的扩展名。然后只需使用MeasurementFormatter根据需要显示它:
Just create a Double extension to convert your meters unit to feet. Then just use MeasurementFormatter to display it as needed:
extension Double {
var metersToFeet: Double {
return Measurement(value: self, unit: UnitLength.meters).converted(to: UnitLength.feet).value
}
}
游乐场
Playground
let measurementFormatter = MeasurementFormatter()
measurementFormatter.locale = Locale(identifier: "en_US")
measurementFormatter.unitOptions = .providedUnit
measurementFormatter.numberFormatter.maximumFractionDigits = 0
measurementFormatter.unitStyle = .long
let meters: Double = 1839
let localizedString = measurementFormatter.string(from: Measurement(value: meters.metersToFeet, unit: UnitLength.feet))
localizedString // // "6,033 feet"
这篇关于使用MeasurementFormatter选择单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!