通过 Picker 更改 @Published var [英] Change a @Published var via Picker
问题描述
我想通过 Picker 更改 @Published var,但我发现它无法编译.
I would like to change a @Published var through the Picker but I found that it fails to compile.
我有一个语言结构:
enum Language: Int, CaseIterable, Identifiable, Hashable {
case en
case zh_hant
var description: String {
switch self {
case.en:
return "English"
case.zh_hant:
return "繁體中文"
}
}
var id: Int {
self.rawValue
}
}
在我的 DataModel 中,我发布了变量 selectedLanguage
And inside my DataModel, I have published the variable selectedLanguage
final class ModelData: ObservableObject {
@Published var currentLanguage: Language = Language.zh_hant
}
我尝试使用选择器让用户更改语言:
I tried to use a picker for the user to change the language:
@EnvironmentObject var modelData: ModelData
在视图主体中:
Picker("Selected Language", selection: modelData.currentLanguage) {
ForEach(Language.allCases, id: \.rawValue) { language in
Text(language.description).tag(language)
}
}.pickerStyle(SegmentedPickerStyle()).padding(.horizontal)
它说无法将‘语言’类型的值转换为预期的参数类型‘绑定’"
It says "Cannot convert value of type 'Language' to expected argument type 'Binding'"
如何直接使用picker修改modelData中的currentLanguage?
How can I modify the currentLanguage in the modelData directly with the picker?
推荐答案
你们非常接近.在绑定到 @Published 属性时,您需要使用 $
:
You were very close. You need to use the $
when making a binding to a @Published property like that:
Picker("Selected Language", selection: $modelData.currentLanguage) {
ForEach(Language.allCases, id: \.id) { language in
Text(language.description).tag(language)
}
}.pickerStyle(SegmentedPickerStyle()).padding(.horizontal)
我还将 id:
更改为 \.id
而不是 \.rawValue
这有点毫无意义,因为它们解析为相同的东西,但在语义上更有意义.
I also changed the id:
to \.id
rather than \.rawValue
which is somewhat meaningless since they resolve to the same thing, but makes a little more sense semantically.
这篇关于通过 Picker 更改 @Published var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!