I have an observedObject that calls to a viewModel (variable vm). The viewModel contains all the user's information already saved. I want to use the value that the user already saved as the selection of the picker. If no data exists yet for the user (in this case their height, I just leave the selection as an empty string.
I'm getting a bunch of issues with my current approach and can't seem to figure it out. The errors include:
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)
}
}
}
}
}
}
}
}
CodePudding user response:
you could try this approach, it's a bit convoluted, but it works for me:
HStack{
if vm.userModel != nil {
Picker(selection: Binding<String> (
get: { vm.userModel!.height },
set: { vm.userModel!.height = $0 }),
label: Text("Height")) {
ForEach(heightOptions, id: \.self){ height in
Text(height)
}
}
}
}
Also add this to the Form
:
.onAppear {
if vm.userModel == nil { vm.userModel = User(height: "") }
}
If vm.userModel
is nil
, there is no user
to set the height of,
no matter what you select.
So you need to create
a user when vm.userModel
is nil
.
Then you can make a selection for that empty
user. You can do this in
.onAppear{ ... }
for example.