In this code below, I want the TextField value to be cleared when the button is selected and the object's clear
method is called (in reality, my class has many properties so I feel like clearing them all calls for a "clear" function).
struct ContentView: View {
@State var object = Object()
var body: some View {
NewView(object: $object)
}
}
struct NewView: View {
@Binding var object: Object
var body: some View {
TextField("Enter some text", text: $object.text)
.border(Color.black, width: 1)
Button("Clear", action: {
object.text = ""
object.clear()
})
}
}
class Object {
var text = ""
func clear(){
self.text = ""
}
}
I've seen other questions about how
- "@State must be defined within the view hierarchy"
- But I think that's already the case here
- "Using onChange or onReceive"
- I don't think that would help me either, or else I'm not sure how to use it correctly to update the view elements
I'm so new to SwiftUI, I really don't know what I don't know - should I be using something like Publishers, or ObservedObjects, or would an Environment object work?
@State
is just for values or structs not classes