问题描述
根据 Apple 关于
但是,如果我为每个视图传递一个 tag
,它就可以工作.
这里发生了什么?苹果文档有错吗?selectedFlavor
变量需要一个 Flavor
类型的值,但是选择器中使用的 id 实际上是一个 String
.
谢谢.
要使 Picker
正常工作,需要识别其元素.
请注意,selectedFlavor
变量的类型为 Flavor
.这意味着 Picker 中的选项应该被标识为 Flavors(而不是 Strings).
但是,在您的代码中,您的 id
属于 String
类型:
var id: String { self.rawValue }
您可以:
- 提供一个
标签
(Flavor
类型):
Text(flavor.rawValue.capitalized).tag(风味)
- 通过提供类型为
Flavor
的自定义id
使Flavor
符合Identifiable
:
var id: Flavor { self }
- 在
ForEach
中明确指定id
参数(Flavor
类型):
ForEach(Flavor.allCases, id: \.self) { ... }
- 将
selectedFlavor
更改为字符串:
@State private var selectedFlavor = Flavor.chocolate.rawValue
According to Apple's documentation regarding Picker in SwiftUI using an Enum, if the enum conforms to the Identifiable
protocol in addition to CaseIterable
, a picker iterating over all cases should update the bound variable natively.
I tested it, and it does not work as expected.
enum Flavor: String, CaseIterable, Identifiable {
case chocolate
case vanilla
case strawberry
var id: String { self.rawValue }
}
struct EnumView: View {
@State private var selectedFlavor = Flavor.chocolate
var body: some View {
VStack {
Picker("Flavor", selection: $selectedFlavor) {
ForEach(Flavor.allCases) { flavor in
Text(flavor.rawValue.capitalized)//.tag(flavor)
}
}
Text("Selected flavor: \(selectedFlavor.rawValue)")
}
}
}
However, if I pass a tag
for each view, it works.
What's happening here? Is the Apple documentation wrong? The selectedFlavor
variable expects a value of type Flavor
, but the id used in the picker is actually a String
.
Thanks.
For a Picker
to work properly, its elements need to be identified.
Note that the selectedFlavor
variable is of type Flavor
. Which means the options in the Picker should be identified as Flavors (not Strings).
However, in your code your id
is of type String
:
var id: String { self.rawValue }
You can either:
- provide a
tag
(of typeFlavor
):
Text(flavor.rawValue.capitalized)
.tag(flavor)
- conform
Flavor
toIdentifiable
by providing a customid
of typeFlavor
:
var id: Flavor { self }
- specify the
id
parameter (of typeFlavor
) explicitly in theForEach
:
ForEach(Flavor.allCases, id: \.self) { ... }
- change the
selectedFlavor
to be a String:
@State private var selectedFlavor = Flavor.chocolate.rawValue
这篇关于由枚举驱动的 SwiftUI 选择器:值未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!