Why does this SwiftUI Picker code not work?

前端 未结 2 1544
春和景丽
春和景丽 2021-01-14 08:19

Xcode: 11.2.1

The code below is for a simple form with two components; a Picker (to select a letter) and a Text (to display the selected letter). The code compiles

相关标签:
2条回答
  • 2021-01-14 08:55

    Just for the record, I'm answering my own question based on the accepted answer above and my increased knowledge as a result of that answer. In the question I was not selecting a letter from the array but the index of the letter in the array. So, based on the insight, an alternative working solution might be:

    struct ContentView: View {
    
        @State private var letterIndex = 0
        private let letters = ["Alpha", "Bravo", "Charlie"]
    
        var body: some View {
            NavigationView {
                Form {
                    Picker("Select a letter", selection: $letterIndex) {
                        ForEach(0..<letters.count) { index in
                            Text(self.letters[index])
                        }
                    }
                    Text("Selected letter: \(letters[letterIndex])")
            }
            .navigationBarTitle("Main Menu")
        }
    }
    
    0 讨论(0)
  • 2021-01-14 09:07

    ForEach types inside Picker should be aligned with selection type.

    Here is a corrected code that should work for you:

    @State private var letter = ""
    private let letters = ["Alpha", "Bravo", "Charlie"]
    
    var body: some View {
        NavigationView {
            Form {
                Picker("Select a letter", selection: $letter) {
                    ForEach(letters, id: \.self) { option in
                        Text(option)
                    }
                }
                Text("Selected letter: \(letter)")
            }
            .navigationBarTitle("Main Menu")
        }
    }
    
    0 讨论(0)
提交回复
热议问题