ohms
ohms

Reputation: 33

SwiftUI segmented picker default state as nil

I'm using a segmented picker in a form to answer simple "Yes" and "No" questions. Can the segmented picker initial state be set to nil so that neither yes or no is highlighted/selected on appear?

@State private var equipmentCheck = 0
private var answers = ["Yes", "No"]

var body: some View {
    NavigationView {
        Form {
            Section(header: Text("Questions")) {
                Text("Have the plant and equipment been checked?")
                Picker("", selection: $equipmentCheck) {
                    ForEach(0 ..< answers.count, id: \.self) {
                        Text("\(self.answers[$0])")
                    }
                }
                .pickerStyle(SegmentedPickerStyle())
                .padding()
            }
        }
    }
}

Upvotes: 3

Views: 1489

Answers (2)

vacawama
vacawama

Reputation: 154711

It seems that if you set the selected value to an index that is not in your segmented control, then none of the values are highlighted.

For example:

@State private var equipmentCheck = -1

works.

I’m looking for documentation that confirms that this is guaranteed to work, but have found none.

The documentation for selectedSegmentIndex of UIKit’s UISegmentedControl says to set the value to -1 to remove the selection, so it seems reasonable to do so here as well.

Upvotes: 2

Asperi
Asperi

Reputation: 258443

Here is a possible approach. Tested & worked with Xcode 11.4 / iOS 13.4

@State private var equipmentCheck: Int?        // << here !!
private var answers = ["Yes", "No"]

var body: some View {
    NavigationView {
        Form {
            Section(header: Text("Questions")) {
                Text("Have the plant and equipment been checked?")
                Picker("", selection: $equipmentCheck) {
                    ForEach(0 ..< answers.count, id: \.self) {
                        Text("\(self.answers[$0])")
                           .tag(Optional($0))           // << here !!
                    }
                }
                .pickerStyle(SegmentedPickerStyle())
                .padding()
            }
        }
    }
}

Upvotes: 4

Related Questions