runemonster
runemonster

Reputation: 209

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)
    }

}

Upvotes: 2

Views: 812

Answers (2)

CameronBaba
CameronBaba

Reputation: 83

Change your selection binding data type to string

@State var choice: String = "Please Select One"

Then minor changes on the Picker logic

var settings = ["Please Select One", "ch1", "ch2", "ch3"]
Picker("Options", selection: $choice) {
    ForEach(settings, id: \.self) {
        Text($0)
    }
}

And you're done.

Upvotes: 0

Asperi
Asperi

Reputation: 257729

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))
                }
            }
        }
    }
}

Upvotes: 1

Related Questions