Clear a TextField on button tap in SwiftUI

In this tutorial, how to clear a TextField on a button tap in SwiftUI.

We can programmatically clear or empty a TextField on a button tap by modifying the value bound to the TextField in SwiftUI. For that, we need to create a @State variable to hold the TextField value and then modify that state variable to clear the TextField.

You can also check out the link to  Change the TextField values programmatically in SwiftUI

Example

import SwiftUI

struct ContentView: View {
    @State private var text: String = ""

    var body: some View {
        VStack {
            TextField("Enter text", text: $text)
                .font(.title2)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()

            Button("Clear Text") {
                text = "" // Set the text to an empty string to clear the TextField
            }
            .font(.title2)
            .padding()
        }
    }
}

In the above program, the TextField value is bound to the text state variable using text: $text. When we click the “Clear Text” button, it will set the text to an empty string, which will clear the TextField.

So, we can now clear the text that we enter in the TextField by clicking the Clear Text button.

Output:

Clear a TextField on button tap in SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *