SwiftUI 中可选数据类型的选择器? [英] Picker for optional data type in SwiftUI?
问题描述
通常我可以在 SwiftUI 中显示这样的项目列表:
Normally I can display a list of items like this in 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)
}
}
}
}
这很完美,让我可以选择我想要的任何水果.但是,如果我想将 fruit
切换为可以为空(又名可选),则会导致问题:
This works perfectly, allowing me to select whichever fruit I want. If I want to switch fruit
to be nullable (aka an optional), though, it causes problems:
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)
}
}
}
}
选择的水果名称不再显示在第一屏上,无论我选择什么选择项,它都不会更新水果值.
The selected fruit name is no longer displayed on the first screen, and no matter what selection item I choose, it doesn't update the fruit value.
如何将 Picker 与可选类型一起使用?
How do I use Picker with an optional type?
推荐答案
标签必须与正在包装的绑定完全匹配的数据类型.在这种情况下,提供给 tag
的数据类型是 Fruit
但 $fruit.wrappedValue
的数据类型是 Fruit?
>.您可以通过在 tag
方法中转换数据类型来解决此问题:
The tag must match the exact data type as the binding is wrapping. In this case the data type provided to tag
is Fruit
but the data type of $fruit.wrappedValue
is Fruit?
. You can fix this by casting the datatype in the tag
method:
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 as Fruit?)
}
}
}
}
奖励:如果您想要 nil
的自定义文本(而不是空白),并希望允许用户选择 nil
(注意:这里要么全部要么全无),您可以为 nil
包含一个项目:
Bonus: If you want custom text for nil
(instead of just blank), and want the user to be allowed to select nil
(Note: it's either all or nothing here), you can include an item for nil
:
struct FruitView: View {
@State private var fruit: Fruit?
var body: some View {
Picker(selection: $fruit, label: Text("Fruit")) {
Text("No fruit").tag(nil as Fruit?)
ForEach(Fruit.allCases) { fruit in
Text(fruit.rawValue).tag(fruit as Fruit?)
}
}
}
}
不要忘记转换 nil
值.
这篇关于SwiftUI 中可选数据类型的选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!