0

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

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?

1
  • @State is just for values or structs not classes
    – malhal
    Commented Jun 28 at 13:20

2 Answers 2

0

The issue is that you're not linking text property with the others. So, when the text changes, it cannot notify the listener(s), which is TextField:

@Observable //<- add here
class Object {
    ...
}

Or fallback to the previous version:

class Object: ObservableObject {
    @Published var text = ""
    ...
}
0

Simple @State var ... work with type object (eg struct Object), not suited for classes, unless you use the @Observable class Object....

Note, the way TextField work, you need to press the return button to submit before the clear button can take effet.

struct Object {
    var text = ""
    
    mutating func clear() {
        self.text = ""
    }
}

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") {
            object.text = ""
        }
    }
}

Alternatively, use

 @Observable class Object {
     var text = ""
 }

Not the answer you're looking for? Browse other questions tagged or ask your own question.