SwiftUI TextField clearbutton how?

How can you add the clearbutton to a TextField?

Post not yet marked as solved Up vote post of bitsflew Down vote post of bitsflew
9.0k views

Replies

I do not know a direct way to do it like with UITextField.

There are still a lot of limits to SwiftUI.


But you could put the textField in a containes witha clearbutton…

The cleanest solution to this problem is to define a view modifier. For example:


struct ClearButton: ViewModifier {
    @Binding var text: String
   
    public func body(content: Content) -> some View {
        HStack {
            content
            Button(action: {
                self.text = ""
            }) {
                Image(systemName: "multiply.circle.fill")
                    .foregroundColor(.secondary)
            }
        }
    }
}


The following demonstrates use of this view modifier:


struct ClearButton: ViewModifier {
    @Binding var text: String
   
    public func body(content: Content) -> some View {
        HStack {
            content
            Button(action: {
                self.text = ""
            }) {
                Image(systemName: "multiply.circle.fill")
                    .foregroundColor(.secondary)
            }
        }
    }
}

Helpful suggestion thank you...

Maybe you intended to include code for the use of the ViewModifier?

struct MPTextField: View {
   
  let title: String
  @Binding var text: String
  @State private var isEditing: Bool = false
  private var isClear: Bool {
    return self.isEditing && !self.text.isEmpty
  }
   
  init(_ title: String, text: Binding<String>) {
    self.title = title
    self._text = text
  }
   
  var body: some View {
    ZStack(alignment: .trailing) {
      TextField(self.title,
           text: self.$text) { isEditing in
        self.isEditing = isEditing
      } onCommit: {
        self.isEditing = false
      }
      .padding(.trailing, self.isClear ? 18 : 0)
       
      if self.isClear {
        Button {
          self.text = ""
        } label: {
          Image(systemName: "multiply.circle.fill").foregroundColor(.secondary)
        }
        .buttonStyle(PlainButtonStyle())
      }
    }
    .frame(alignment: .trailing)
  }
}

Add this to your SwiftUI view and all your TextField in that view will start displaying clear button

init() {
  UITextField.appearance().clearButtonMode = .whileEditing
}

Just set the value of the variable that your TextField is bound to to "".