Search code examples
swiftswiftuipicker

Set default starting point on Picker


How do I set the starting value to the text "Please Select One" inside the picker. Currently it defaults to the first choice in the array.

This is the state

@State var Choioce = 0

This is the picker

var settings = ["ch1", "ch2", "ch3"]
Picker("Options", selection: $Choioce) {
    Text("Please Select One")
    ForEach(0 ..< settings.count) { index in
        Text(self.settings[index])
            .tag(index)
    }

}

Solution

  • Make selection optional, like below. Tested with Xcode 12 / iOS 14

    demo

    struct ContentView: View {
        @State var Choioce: Int?               // << here !!
        var settings = ["ch1", "ch2", "ch3"]
    
        var body: some View {
            VStack {
                Text("Selection: \(Choioce == nil ? "<none>" : settings[Choioce!])")
                Picker("Options", selection: $Choioce) {
                    Text("Please Select One").tag(Optional<Int>.none)
                    ForEach(0 ..< settings.count) { index in
                        Text(self.settings[index])
                            .tag(Optional(index))
                    }
                }
            }
        }
    }