SwiftUI: Add ClearButton to TextField

Use .appearance() to activate the button

var body: some View {
    UITextField.appearance().clearButtonMode = .whileEditing
    return TextField(...)
}

For reuse try with this:

func TextFieldUIKit(text: Binding<String>) -> some View{
    UITextField.appearance().clearButtonMode = .whileEditing
    return TextField("Nombre", text: text)
}

Use ZStack to position the clear button appear inside the TextField.

TextField("Some Text" , text: $someBinding).modifier(ClearButton(text: $someBinding))

struct ClearButton: ViewModifier
{
    @Binding var text: String

    public func body(content: Content) -> some View
    {
        ZStack(alignment: .trailing)
        {
            content

            if !text.isEmpty
            {
                Button(action:
                {
                    self.text = ""
                })
                {
                    Image(systemName: "delete.left")
                        .foregroundColor(Color(UIColor.opaqueSeparator))
                }
                .padding(.trailing, 8)
            }
        }
    }
}

clear button inside TextView


=== solution 1(best): Introspect https://github.com/siteline/SwiftUI-Introspect

import Introspect
TextField("", text: $text)
    .introspectTextField(customize: {
        $0.clearButtonMode = .whileEditing
    })

=== solution 2: ViewModifier

public struct ClearButton: ViewModifier {
    @Binding var text: String

    public init(text: Binding<String>) {
        self._text = text
    }

    public func body(content: Content) -> some View {
        HStack {
            content
            Spacer()
            Image(systemName: "multiply.circle.fill")
                .foregroundColor(.secondary) 
                .opacity(text == "" ? 0 : 1)
                .onTapGesture { self.text = "" } // onTapGesture or plainStyle button
        }
    }
}

Usage:

@State private var name: String

...

Form {
    Section() {
        TextField("NAME", text: $name).modifier(ClearButton(text: $name))
    }
}

=== solution 3: global appearance

UITextField.appearance().clearButtonMode = .whileEditing

Tags:

Swiftui