创建一个返回字符串的选择器

问题描述 投票:0回答:1

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)
  }

谢谢大家的帮助。

swift xcode swiftui picker
1个回答
0
投票

您可以尝试这样的事情:

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)
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.