Today I spent too much time looking at a bit of code that wasn't working. Here's the problem: the following picker uses a struct to both display values, as well as save the selection. Only problem is; it doesn't work. It displays correctly, but you can't select it; essentially it's read-only.
struct UnselectablePicker: View { struct Language: Identifiable, Hashable { var title: String var id: String } var languages: [Language] = [ Language(title: "English", id: "en-US"), Language(title: "German", id: "de-DE"), Language(title: "Korean", id: "ko-KR"), Language(title: "Dutch", id: "nl-NL") ] @State private var selectedLanguage = UnselectablePicker.Language(title: "German", id: "de-DE") var body: some View { Picker(selection: $selectedLanguage, label: Text("Front Description")) { ForEach(self.languages) { Text($0.title) } }.pickerStyle(.segmented) } }
Did you spot it? The problem is in the ForEach. The picker works with the following correction:
ForEach(self.languages, id: \.self) { // ... }
Alternatively, add a tag.
ForEach(self.languages) { Text($0.title) .tag($0.title) }