Search code examples
swiftswiftuilabelpicker

SwiftUI: The Picker label text is not appearing and I can't seem to modify it


When I create a menu style picker I am only seeing the picker options displayed and not my label text.

This is using the updated code: Picker(selection:, content:, label), but I get the same result when using the deprecated for versions code as well: Picker(selection:, label:, content)

This is my Code:

    private var addGenderSection: some View {
        VStack(spacing: 20) {
            Spacer()
            
            Text("What's your gender?")
                .font(.largeTitle)
                .fontWeight(.semibold)
                .foregroundStyle(.white)
            
            Picker(selection: $gender) {
                Text("1").tag(1)
                Text("2").tag(2)
            } label: {
                Text("Select a gender")
                    .font(.headline)
                    .foregroundStyle(.purple)
                    .frame(height: 55)
                    .frame(maxWidth: .infinity)
                    .background(Color.white)
            }
            .pickerStyle(.menu)

            
            Spacer()
            Spacer()
        }
        .padding(30)
    }

This is my result:

enter image description here

Expected result:

Not Selected:

enter image description here

Selected:

enter image description here


Solution

  • As @workingdog said, Menu is a better solution in this circumstance. Actually, you can't customize the pickerStyle(.menu) appearance. Try this:

    private var genders = [1, 2]
    @State private var gender: Int?
    
    ...
    Menu {
        Button("\(genders[0])") {
            gender = 1
        }
        Button("\(genders[1])") {
            gender = 2
        }
    } label: {
        Text(gender == nil ? "Select a gender" : "Gender is \(gender!)")
            .foregroundColor(.purple)
            .frame(maxWidth: .infinity)
    }
    .frame(maxWidth: .infinity)
    .background {
        Color.white
            .frame(height: 55)
            .cornerRadius(10)
    }
    

    enter image description here