Hello everyone
我正在创建一个表单,允许我修改@EnvironmentObject变量的数据。
因此,我希望能够创建一个返回字符串的Picker。但是,在尝试了许多失败之后,我的印象是Picker无法返回String。
任何人都会想到一个返回字符串的Picker(也许通过UIKit吗?)。
这是我的代码:
struct UserStruct {
var firstName: String
var lastName: String
var birthDate: Int
var city: String
var postalCode: Int
var street: String
var streetCode: String
var country: String
}
class User: ObservableObject {
@Published var userProfile = UserStruct()
// Other stuff here
}
// Then in my FormView:
// I declare the object as @EnvironmentObject
@EnvironmentObject var userStore: User
// I declare an array which contains all the country for the picker
let country = ["France", "Russie", "USA"]
// In my var body: some View...
// Trying to change the value of country of the userStore object
Picker(selection: $userStore.userProfile.country, label: Text("Make a choice")) {
ForEach(0 ..< country.count) { index in
Text(self.country[index]).tag(index)
}
谢谢大家的帮助。
您可以尝试这样的事情:
let country = ["France", "Russie", "USA"]
@State var countrySelection = 0
Picker(selection: Binding(get: {
self.countrySelection
}, set: { newVal in
self.countrySelection = newVal
self.userStore.userProfile.country = self.country[self.countrySelection]
}), label: Text("Make a choice")) {
ForEach(0 ..< country.count) { index in
Text(self.country[index]).tag(index)
}
}