Home > Net >  Set picker default no clickable value as title
Set picker default no clickable value as title

Time:05-01

I'm trying to develop a Picker with a field that corresponds to the title. The problem is that I'm not understanding how to use the title field of the Picker view.

This is the code. The problem is that the Picker is taking as title the string "Spain". Instead I want the title "Select country" which is visible until the user select a field.

First things that the user see

View once the user press the Picker

struct CustomPicker: View {
    
    @State private var selection = "Select country"
    let colors = ["Spain", "France"]
    
    var body: some View {
        VStack(alignment: .leading, spacing: 4, content: {
    
            HStack(spacing: 15) {
                
                Picker("Select country", selection: $selection) {
                    ForEach(colors, id: \.self) {
                        Text($0)
                    }
                }
                .pickerStyle(DefaultPickerStyle())
            }
            
            .padding(.horizontal, 20)
        })
            .frame(height: 50)
            .background(.white)
            .cornerRadius(10)
            .padding(.horizontal, 20)
    }
}

CodePudding user response:

What you're trying to do doesn't come standard with SwiftUI. You would have to custom make your UI for this (and that might not be hard). Depending on how much you're willing to compromise, you can have what you want with a slight tweak of your code. This is what a picker looks like within a List (as well as your Picker in the List).

To do this I modified your code slightly to include an enum for the countries.

enum Country: String, CaseIterable, Identifiable {
    case spain, france, germany, switzerland
    var id: Self { self }
}

struct CustomPicker: View {
    
    @State private var selection: Country = .spain
    
    var body: some View {
        NavigationView {
            List {
                Picker("Select Country", selection: $selection) {
                    ForEach(Country.allCases, id: \.self) {
                        Text($0.rawValue.capitalized)
                            .tag($0)
                    }
                }
                Picker("Select Country", selection: $selection) {
                    ForEach(Country.allCases, id: \.self) {
                        Text($0.rawValue.capitalized)
                            .tag($0)
                    }
                }
                .pickerStyle(.menu)
            }
            .navigationBarTitleDisplayMode(.inline)
            .navigationTitle("Country Picker")
        }
    }
}

showing different Picker styles within a List

  • Related