I’m hoping someone can help me with this issue that’s driving me nuts.
I want to use the formatted() modifier with Measurements so I can get locale specific units, and it’s working great for mass and temperature.
I correctly get oz/g and F/C but for volume I’m getting cm3/in3 instead of ml/floz.
I realize that is a Volumetric unit, but It’s not the one i want.
Text("(Measurement(value: Double(volume), unit: UnitVolume.milliliters).formatted())")
Text("(Measurement(value: Double(mass), unit: UnitMass.grams).formatted())")
Text("(Measurement(value: Double(temp), unit: UnitTemperature.celsius).formatted())")
I know I can do this
Text("(Measurement(value: Double(brew.water), unit: UnitVolume.milliliters).formatted(.measurement(width: .abbreviated, usage: .asProvided, numberFormatStyle: .number)))")
But then I have to figure out the locale myself.
Is there a way to this with the builtins in swiftui?
Thanks in advance
2
Answers
Your last attempt is close. Just change the usage to
.liquid
instead ofasProvided
.This gives me the result as "fl oz" with a locale of en_US.
Note that
MeasurementFormatUnitUsage<UnitVolume>.liquid
is only available as of iOS 16.0 so this solution won’t work with iOS 15.You can use
converted
andMeasurementFormatter
In its simplest form it would look something like
But in an
extension
you can add customizations that can be reused and it works similar toformatted
but allows for iOS 14+.And then your
View
would evolve to look something likeYou can also extend
Measurement
itself and add a method that provides the string automatically.Then you don’t have to use
formatter
you can just calltoString()
which would allow for an answer that works with all SwiftUI versions.To show locale adjusted measurements you can just add
.current
to theLocale
Then just set the
unitOptions
argument tonil
when you want the units to show adjusted by locale