SwiftUI Picker Label with PickerStyle .menu in iOS HowTo
Asked Answered
F

1

8

For some reason Apple decided to drop Label support for Pickers (tested in iOS15 and iOS16)

For example:

Picker(selection: $gender,
                   label:
                    "Select your gender"
                   , content: {
                            Text(Gender.male.rawValue).tag(Gender.male)
                            Text(Gender.female.rawValue).tag(Gender.female)
                            Text(Gender.nobinary.rawValue).tag(Gender.nobinary)
            }).pickerStyle(.automatic)
                    .font(.largeTitle)
                    .accentColor(.white)

ignores the label view.

So howto solve that?

Fimbriation answered 20/7, 2022 at 6:50 Comment(0)
F
17

To add a Label View out of the box without custom View one has to use Picker in Menu View embedded. Now one can use modifier on the Menu Label Views and even use logic for the selected text.

Menu {
    Picker(selection: $gender,
        label: EmptyView(),
        content: {
            Text(Gender.male.rawValue).tag(Gender.male)
            Text(Gender.female.rawValue).tag(Gender.female)
            Text(Gender.nobinary.rawValue).tag(Gender.nobinary)
        }).pickerStyle(.automatic)
           .accentColor(.white)
    } label: {
        Text(gender == .unselected ? "Select your gender" : gender.rawValue)
            .font(.title3)
            .frame(maxWidth: .infinity)
            .frame(height: 55)
            .background(.white)
            .cornerRadius(10)
            .accentColor(.pink)
}
Fimbriation answered 20/7, 2022 at 6:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.