I’ve created a weather model which includes a @Published var called metricSelected:
@Published var metricSelected = true
I’m having problems binding this to a toggle UI element. I am able to reference the variable in my View - for example with:
HStack {
Text("Feels like ")
.padding()
if model.metricSelected {
Text("\(String(format: "%.0f", model.feelsLike!))")
} else {
Text("\(String(format: "%.0f", model.convertToFarenheit(model.feelsLike!)))")
}
Text(model.metricSelected ? "C" : "F")
}
But if I use this code for a Toggle element - I get an error: “Cannot convert value of type ‘Bool’ to expected argument type ‘Binding’”
Toggle(isOn: model.$metricSelected) {
Text("Metric")
}
I’ve created a really cronky workaround (which works) but I am sure is not the right way. I’ve added a @State var declaration with a new variable called myViewMetricSelected to the view, and then used this to reset the variable in the viewModel:
Toggle(isOn: $myViewMetricSelected) {
Text("Metric")
}.onChange(of: myViewMetricSelected, perform: { value in
model.metricSelected.toggle()
})
Advice would be greatly welcomed! Have been struggling with this for a bit now…