在 Picker 选择中调用 viewModel

Call viewModel in Picker selection

我有一个调用 viewModel(变量 vm)的 observedObject。 viewModel 包含所有已保存的用户信息。我想使用用户已经保存的值作为选择器的选择。如果用户还没有数据(在这种情况下是他们的身高,我只是将选择保留为空字符串。

我目前的方法有很多问题,似乎无法解决。错误包括:

Cannot convert value of type 'String' to expected argument type 'Binding'

Add explicit 'self.' to refer to mutable property of 'PersonalSettingsView'

Chain the optional using '?' to access member 'weight' only for non-'nil' base values

struct PersonalSettingsView: View {
    @ObservedObject var vm = DashboardLogic() //call to viewModel
    
    @State private var height: String = ""
     
    private var heightOptions = ["4'0", "4'1","4'2","4'3", "4'4", "4'5","4'6","4'7","4'8","4'9","4'10","4'11","5'0","5'1", "5'2", "5'3", "5'4", "5'5","5'6","5'7","5'8","5'9","5'10","5'11","6'0","6'1","6'2","6'3","6'4","6'5","6'6","6'7","6'8","6'9","6'10","6'11","7'0","7'1","7'2"] 
    
    var body: some View {
        NavigationView{
            Form{
                Section(header: Text("Health Stats")
                            .foregroundColor(.black)
                            .font(.body)
                            .textCase(nil)){
             
                    HStack{
                        Picker(selection: $vm.userModel?.height ?? "", label: Text("Height")){
                            ForEach(heightOptions, id: \.self){ height in
                                Text(height)
                            }
                        }
                    } 
                }
            }
        }
     }   
   }

你可以试试这个方法,有点复杂,但对我有用:

HStack{
    if vm.userModel != nil {
        Picker(selection: Binding<String> (
            get: { vm.userModel!.height },
            set: { vm.userModel!.height = [=10=] }),
               label: Text("Height")) {
            ForEach(heightOptions, id: \.self){ height in
                Text(height)
            }
        }
    }
}

同时将此添加到 Form:

.onAppear {
    if vm.userModel == nil { vm.userModel = User(height: "") }
}

如果vm.userModelnil,则没有user设置高度, 不管你select。 因此,当 vm.userModelnil 时,您需要 create 一个用户。 然后你可以为那个 empty 用户制作一个 selection。你可以在 .onAppear{ ... } 例如。