struct DevTechieTextFieldClearButtonExample: View { @State private var text = "" init() { UITextField.appearance().clearButtonMode = .whileEditing } var body: some View { VStack { Text("DevTechie") .font(.largeTitle) TextField("Enter something", text: $text) .textFieldStyle(.roundedBorder) } .padding() } }
struct ClearButton: ViewModifier { }
@Binding var text: String
func body(content: Content) -> some View { }
ZStack(alignment: .trailing) { content if !text.isEmpty { Button { text = "" } label: { Image(systemName: "multiply.circle.fill") .foregroundStyle(.gray) } .padding(.trailing, 8) } }
extension View { func clearButton(text: Binding<String>) -> some View { modifier(ClearButton(text: text)) } }
struct ClearButton: ViewModifier { @Binding var text: String func body(content: Content) -> some View { ZStack(alignment: .trailing) { content if !text.isEmpty { Button { text = "" } label: { Image(systemName: "multiply.circle.fill") .foregroundStyle(.gray) } .padding(.trailing, 8) } } } }extension View { func clearButton(text: Binding<String>) -> some View { modifier(ClearButton(text: text)) } }
struct DevTechieTextFieldClearButtonExample: View { @State private var text = "" var body: some View { VStack { Text("DevTechie") .font(.largeTitle) TextField("Enter something", text: $text) .textFieldStyle(.roundedBorder) .clearButton(text: $text) } .padding() } }
Image(systemName: "delete.backward.fill").foregroundStyle(.orange.gradient.opacity(0.6))
With that we have reached the end of this article. Thank you once again for reading. If you liked this, don’t forget to 👏 and follow 😍. Also subscribe to our weekly newsletter at https://www.devtechie.com