Swiftui: align selected text in picker to leading edge
Asked Answered
H

2

6

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)
                        }
                    }
                }
            }
        }
    }
}
Hut answered 25/5, 2021 at 14:3 Comment(2)
Seems to be a problem only when using Picker inside a Form...Moleskins
@Moleskins actually I need to go to a separate screen to select some value from the array, that's why the Form is necessary in this caseHut
T
7

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()
                            }
                        }
                    }
                }
            }
        }
    }
}
Trine answered 25/5, 2021 at 14:37 Comment(0)
C
6

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

Cureall answered 10/2, 2023 at 0:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.