I am not able to access use the switch. I want if the switch is on, it should come up with a text field and if it is off the value of the variable should be zero. Can anyone help me with this. I have tried to use two different methods. One by using .Onchange and one without using .Onchange. When I use .Onchange, it comes up with a waning that the result of text field is unused. And when I don’t use .onAppear it doesn’t accept (userSettings.load = 0) but the text field works fine then. I don’t understand what I am doing wrong here.The variables are defined as :
struct TwoView: View {
@EnvironmentObject var userSettings: UserSettings
@State var load: Bool = false
var body: some View {
NavigationView {
VStack {
Form {
Toggle("Casual loading", isOn: $load)
.onChange(of: load) { value in
if load == false
{
userSettings.loadrate = 0
}
else
{
TextField("Casual Loading", value: $userSettings.loadrate, format: .number)
}
}
}
}
}
}
}
class UserSettings: ObservableObject
{
@Published var loadrate = Float()
}
2
Answers
Right now, you’re using
TextField
outside of the view hierarchy, and just inside theonChange
. In fact, as you mentioned, Xcode is giving you a warning about the fact that it is unused.To solve this, you can use an
if
clause inside the hierarchy itself:TextField is a view element and it shouldn’t be inside a closure. It should be a child of a view.
Similarly, assignment is not a view element, so it is not accepted to be in a view.
So, what you need to do is put
userSettings.loadrate = 0
into.onChange
, and putTextField
outside.onChange
.I’m not sure what exactly is your expected result, but here is an example.