Use MeasurementFormatter to display meters as feet

穿精又带淫゛_ 提交于 2019-12-12 19:17:20

问题


I'm having trouble getting the new MeasurementFormatter class to give me results in appropriate units. I have values in meters that I want to display in localized strings, either meters or feet depending on the user's locale.

I have this:

let meters : Double = 10
let metersMeasurement = Measurement(value: meters, unit: UnitLength.meters)

let measurementFormatter = MeasurementFormatter()
measurementFormatter.locale = Locale(identifier: "en_US")

let localizedString = measurementFormatter.string(from: metersMeasurement)

This gives me a string of "0.006mi". It's correct, I guess, but converting 10 meters to miles is kind of ridiculous. What I want is "32.8ft".

The .providedUnit option on MeasurementFormatter isn't helpful-- that just gives me a result in meters.

I could look up the current locale and handle this myself, but that's exactly the kind of thing that MeasurementFormatter is supposed to make unnecessary. Is there some way to get it to do what I need?


回答1:


You should set the formatter's unitOptions to naturalScale:

let measurementFormatter = MeasurementFormatter()
measurementFormatter.unitOptions = .naturalScale

And you should only set the locale if you want every user in any locale to see the value in the specific locale.



来源:https://stackoverflow.com/questions/39841338/use-measurementformatter-to-display-meters-as-feet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!