Jim
Jim

Reputation: 65

how to detect when clear button tapped on SwiftUI Textfield with Introspect

I'm using Introspect on a SwiftUI TextField to add a clear button to the text field. When the clear button is tapped, I want to toggle a boolean in my view model.

   TextField("", text: $viewModel.title)
              .textFieldStyle(.roundedBorder)
              .introspectTextField(customize: { $0.clearButtonMode = .always })
              .focused($isFocused)
              .submitLabel(.done)

How can execute code when the clear button is tapped? Introspect makes UIKit methods available for the Swift UI Text Field. So the question might really be how do I execute some code on the tap of the clear button on a UIKIt UITextField.

Upvotes: 1

Views: 952

Answers (1)

Tolga Katas
Tolga Katas

Reputation: 375

enter image description here

Try this, make a view modifier:

struct ClearButton: ViewModifier {
@Binding var text: String

func body(content: Content) -> some View {
    HStack {
        content
        
        if !text.isEmpty {
            Button(
                action: { self.text = "" },
                label: {
                    Image(systemName: "delete.left")
                        .foregroundColor(Color(UIColor.opaqueSeparator))
                }
            )
        }
     } }
}

and the ContentView

struct ContentView: View {
@State var sampleText: String = ""

var body: some View {
    NavigationView {
        Form {
            Section {
                TextField("Type in here...", text: $sampleText)
                    .modifier(ClearButton(text: $sampleText))
                    .multilineTextAlignment(.leading)
            }
        }
        .navigationTitle("Clear example")
    }
}

}

You can execute what you want in the Button's action:

Upvotes: 1

Related Questions