SwiftUI – How can I create a picker (to choose a person’s body weight and height) to display imperial/metric measurement based on their locale?

  Kiến thức lập trình

I am newish to SwiftUI. I am creating a picker, that will let user choose their body weight (and similarily for their height). As you know, in US (and a few other countries), people use imperial measurements (pounds, feet, etc); while in most other countries, people use metric system (kilograms, meters, etc). How can I make this picker easily and accurately adapt to the user’s region/locale? For example, if user’s region uses metric system, display [40kg, 42.5kg, 45kg, 47.5kg, …. 300kg]; if imperial, display [80lb, 85lb, 90lb, …, 600lb]

This is my draft code that basically hard-coded things for imperial measurement:

import SwiftUI

struct SetMyWeightView: View {
    
    // This works for imperial system. But how I can make it work for both imperial and metric system? For example, if user's region uses metric system, display [40kg, 42.5kg, 45kg, 47.5kg, .... 300kg]; if imperial, display [80lb, 85lb, 90lb, ..., 600lb]

    @State private var myWeight: Int?
    
    var body: some View {
        Form {
            Section {
                Picker("", selection: $myWeight) {
                        // Offer user an option to hide their weight
                        Text("Hide").tag(nil as Int?)
                    
                        // Choose from a list [80, 85, 90, ..., 600]
                        ForEach(Array(stride(from: 80, to: 601, by: 5)), id: .self) { weight in
                            Text("(weight) lb").tag(weight as Int?)
                        }
                }
                .pickerStyle(.wheel)
            } header: {
                Text("Weight")
            }
        }
    }
}

#Preview {
    SetMyWeightView()
}

enter image description here

LEAVE A COMMENT