SwiftUI: How to add a clear button to a textfield

Martin Albrecht
3 min readSep 24, 2020
Photo by Ramshid ekl on unsplash.com

There are numerous reasons a user could want to clear a value inside a text field, whether it’s a typo or just for entering completely new things and everyone knows how cumbersome it can become to clear long text on a mobile device inside a small field.

Clear button inside a text field

The TextField element of the SwiftUI framework does not have such a feature built-in, so you’d have to build your own solution for that. In this article I want to show how to accomplish a simple clear button inside a SwiftUI TextField element.

Note: XCode 11.x, Swift 5.x, and iOS 13.x are required. It’s assumed you already have some knowledge about programming in Swift and SwiftUI, how to build apps, and implement your own views in them. This is not a tutorial to teach you the basics.

After initializing a new project we need to create a simple view modifier which we will apply later to our text field. The view modifier has the tasks to check for content in the text field element and display a clear button inside of it, if content is available. It also handles taps on the button and clears the content.

Let’s have a look at that view modifier:

The code itself should be self explanatory and easy to understand as there is no fancy logic included in our tasks.

We just wrap the textfield inside a HStack and add the button, if the text field is not empty. The button itself has a single action of deleting the value of the text field.

For the clear icon we use the delete.left icon from the SF Symbols 2 library by Apple, but you could also use another one or even your own custom one.

The binding of the modifier is the same as the one we apply to the text field. Without it we would not be able to check for content or clear the field itself.

Inside the ContentView.swift we now simply add a TextField element and apply our modifier to it — that’s all!

The navigation view and form inside of the ContentView are not required. You could also just add the TextField inside the body, but with a form it’s much clearer and beautiful. 🙈

And so our final result looks like this:

The text field with the clear button in action

--

--