Home > Enterprise >  SwiftUI Manually control the submission of Text Filed
SwiftUI Manually control the submission of Text Filed

Time:09-27

TextField("", text: $searchText, onCommit: { print("Commit") })
Button(action: {
    searchText = "test" 
    // Do Something
}) { Text("Search test") }

How do I make the Text Filed submit when I press the button

CodePudding user response:

you could try something equivalent, such as:

struct ContentView: View {
    @State var searchText = ""
    
    var body: some View {
        TextField("", text: $searchText, onCommit: { onMySubmit() })
        // ios15
        // .onSubmit {
        //    onMySubmit()
        // }
        Button(action: {
            searchText = "test"
            onMySubmit()
        }) {
            Text("Search test")
        }
    }
    
    func onMySubmit() {
        print("-----> onMySubmit searchText: \(searchText)")
    }
    
}

EDIT1: press the button on the another view, question.

The approach I show is very appropriate in that case as well. Include the onMySubmit into a ObservableObject class, such as:

class MyModel: ObservableObject {
    
    @Published var searchText = ""
    
    ...
    
    func onMySubmit() {
        print("-----> onMySubmit searchText: \(searchText)")
    }

} 

struct ContentView: View {
    @StateObject var myModel = MyModel()
    
    var body: some View {
        TextField("", text: $myModel.searchText, onCommit: { myModel.onMySubmit() })
        // ios15
        // .onSubmit {
        //    myModel.onMySubmit()
        // }
        Button(action: {
            myModel.searchText = "test"
            myModel.onMySubmit()
        }) {
            Text("Search test")
        }
        
        // pass myModel to any other view you want, and
        // use it as shown above
        
    }
}

Pass the model around, either directly or using environment if you desire, and use it as I described in my answer. If you do not know how to use ObservableObject there are some good info on SO and lots of tutorials online.

  • Related