【问题标题】:Create a Picker that returns a String创建一个返回字符串的 Picker
【发布时间】:2020-04-04 02:35:15
【问题描述】:

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】:

    你可以试试这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2019-11-06
      • 2019-12-06
      相关资源
      最近更新 更多