通常我可以在 SwiftUI 中显示这样的项目列表:
enum Fruit {
case apple
case orange
case banana
}
struct FruitView: View {
@State private var fruit = Fruit.apple
var body: some View {
Picker(selection: $fruit, label: Text("Fruit")) {
ForEach(Fruit.allCases) { fruit in
Text(fruit.rawValue).tag(fruit)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这非常有效,让我可以选择我想要的任何水果。但是,如果我想切换fruit为可空(又名可选),则会导致问题:
struct FruitView: View {
@State private var fruit: Fruit?
var body: some View {
Picker(selection: $fruit, label: Text("Fruit")) {
ForEach(Fruit.allCases) { fruit in
Text(fruit.rawValue).tag(fruit)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
选择的水果名称不再显示在第一屏上,无论我选择什么选择项,它都不会更新水果值。
如何将 Picker 与可选类型一起使用?
swiftui ×1