swiftswiftui

How to show distance in the local measuring system?


I want to show max distance here but I want to show the local measurement system in the area the user is using, 15ft in the U.S etc..

 Text("Effective upto 5 meters.")

in the U.S for example it should say: Effective upto 15ft.

I want it to round I dont want 14.5545ft


Solution

  • SwiftUI does this automatically if you use Measurement

    struct BasicMeaturemeantView: View {
        @State private var measurement: Measurement<UnitLength> = .init(value: 5, unit: .meters)
        var body: some View {
            Text("Effective up to") + Text(measurement, format: .measurement(width: .abbreviated))
        }
    }
    

    if you don't want it you can use asProvided

    Text(measurement, format: .measurement(width: .abbreviated, usage: .asProvided))
    

    if you want to add number formatting you can add that too.

    Text(measurement, format: .measurement(width: .wide, numberFormatStyle: .number.precision(.fractionLength(0..<2))))