Swiftui: align selected text in picker to leading edge

2.4k Views Asked by At

Currently I've a picker included in a Section included in a Form what I'm trying to reach is to align the selected value of the picker to the leading in both iOS 13 and 14, I've tried many solutions such as labelsHidden() but with no result, kindly find the code sample that generates the following screenshot on iOS 14, any help would be appreciated enter image description here

struct ContentView: View {
    @State private var selectedStrength = "Mild"
    let strengths = ["Mild", "Medium", "Mature"]

    var body: some View {
        NavigationView {
            Form {
                Section {
                    Picker("", selection: $selectedStrength) {
                        ForEach(strengths, id: \.self) {
                            Text($0)
                        }
                    }
                }
            }
        }
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

Use the Text() with a Spacer() in a HStack()

struct ContentView: View {
    @State private var selectedStrength = "Mild"
    let strengths = ["Mild", "Medium", "Mature"]

    var body: some View {
        NavigationView {
            Form {
                Section {
                    Picker("", selection: $selectedStrength) {
                        ForEach(strengths, id: \.self) { t in
                            HStack {
                                Text(t)
                                Spacer()
                            }
                        }
                    }
                }
            }
        }
    }
}
0
On

You have to use .frame() and .labelsHidden()

struct ContentView: View {
@State private var selectedStrength = "Mild"
let strengths = ["Mild", "Medium", "Mature"]

var body: some View {
    NavigationView {
        Form {
            Section {
                Picker("", selection: $selectedStrength) {
                    ForEach(strengths, id: \.self) {
                        Text($0)
                    }
                }
                .frame(width: 160, alignment: .leading)
                .labelsHidden()
            }
        }
    }
}

}

tested on IOS 16