iOS development
UITextField customization
iPhone programming
SwiftUI
mobile app design

Adding the Clear Button to an iPhone UITextField

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

UITextField already has built-in support for a clear button, so in most cases you do not need to build one yourself. The standard solution is to set clearButtonMode, and only switch to a custom rightView button when you need custom visuals or extra behavior.

The built-in solution

Apple’s built-in clear button is the simplest and most reliable answer.

swift
1import UIKit
2
3final class SearchViewController: UIViewController {
4    private let searchField: UITextField = {
5        let field = UITextField(frame: .zero)
6        field.borderStyle = .roundedRect
7        field.placeholder = "Search"
8        field.clearButtonMode = .whileEditing
9        return field
10    }()
11
12    override func viewDidLoad() {
13        super.viewDidLoad()
14        view.backgroundColor = .systemBackground
15        searchField.translatesAutoresizingMaskIntoConstraints = false
16        view.addSubview(searchField)
17
18        NSLayoutConstraint.activate([
19            searchField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
20            searchField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
21            searchField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40)
22        ])
23    }
24}

The key line is:

swift
field.clearButtonMode = .whileEditing

Available modes are:

  • '.never'
  • '.whileEditing'
  • '.unlessEditing'
  • '.always'

In standard forms, .whileEditing is the most common choice.

Why the built-in button is usually enough

The built-in button already matches the native editing experience and requires almost no code. It is also better than a custom solution when:

  • you want platform-consistent behavior
  • you do not need analytics or special actions
  • you want minimal maintenance
  • you are using UIKit text fields directly

If the design system does not demand customization, the built-in control is the correct default.

Creating a custom clear button

Sometimes you want a different icon, tracking, haptics, or a completely different editing affordance. In that case, attach a custom button through rightView.

swift
1import UIKit
2
3final class CustomClearTextField: UITextField {
4    private lazy var clearButton: UIButton = {
5        let button = UIButton(type: .system)
6        button.setImage(UIImage(systemName: "xmark.circle.fill"), for: .normal)
7        button.tintColor = .secondaryLabel
8        button.addTarget(self, action: #selector(clearTapped), for: .touchUpInside)
9        return button
10    }()
11
12    override init(frame: CGRect) {
13        super.init(frame: frame)
14        borderStyle = .roundedRect
15        rightView = clearButton
16        rightViewMode = .whileEditing
17    }
18
19    required init?(coder: NSCoder) {
20        fatalError("init(coder:) has not been implemented")
21    }
22
23    @objc private func clearTapped() {
24        text = ""
25        sendActions(for: .editingChanged)
26    }
27}

Calling sendActions(for: .editingChanged) is useful because many forms expect downstream validation or bindings to react when the text changes.

Interface Builder option

If you use storyboards or nibs, you can also set the built-in clear button mode without code by changing the text field’s clear button setting in Interface Builder. That is often enough for simple screens.

Code becomes necessary only when you need dynamic configuration or a custom control.

SwiftUI note

The title mentions UITextField, which is UIKit. In pure SwiftUI, TextField does not expose clearButtonMode directly. The usual SwiftUI pattern is either:

  • wrap UITextField with UIViewRepresentable
  • or add a separate trailing button in SwiftUI layout

So if you are actually using SwiftUI rather than UIKit, the answer changes because the built-in UIKit property is not directly available on the native SwiftUI TextField API.

When to choose custom behavior

Use a custom clear button if you need to:

  • track clear events
  • change the icon or hit area
  • show the button only under custom conditions
  • combine clearing with other side effects

Otherwise, default behavior is preferable because it is simpler and more native.

Common Pitfalls

A common mistake is creating a fully custom button when clearButtonMode would already solve the problem.

Another mistake is forgetting to trigger .editingChanged after clearing custom text, which can leave validation or bindings out of sync.

A third mistake is assuming the UIKit answer applies directly to pure SwiftUI TextField without a wrapper.

Summary

  • The standard UIKit answer is textField.clearButtonMode = .whileEditing.
  • Use the built-in clear button unless you need custom visuals or behavior.
  • For custom control, attach a button through rightView.
  • Trigger editing change actions if your custom clear logic should update the rest of the form.
  • In SwiftUI, you usually need a wrapper or a separate trailing button pattern.

Course illustration
Course illustration

All Rights Reserved.