iOS
UITextField
Swift
Text Selection
Programming

Programmatically Select all text in UITextField

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

To select all text in a UITextField, the field must be active and you must assign a full UITextRange to selectedTextRange. The usual mistake is trying to set the selection before the text field becomes first responder, which makes the call appear to do nothing.

Basic Selection Pattern

The core idea is:

  1. make the text field first responder
  2. build a range from beginningOfDocument to endOfDocument
  3. assign that range to selectedTextRange

Here is the direct Swift version:

swift
1import UIKit
2
3func selectAll(in textField: UITextField) {
4    textField.becomeFirstResponder()
5
6    if let range = textField.textRange(
7        from: textField.beginningOfDocument,
8        to: textField.endOfDocument
9    ) {
10        textField.selectedTextRange = range
11    }
12}

If the field is on screen and able to become first responder, that selects the full text.

A View Controller Example

This is a realistic example with a button that selects the text programmatically:

swift
1import UIKit
2
3final class ViewController: UIViewController {
4    private let textField = UITextField()
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8        view.backgroundColor = .systemBackground
9
10        textField.borderStyle = .roundedRect
11        textField.text = "Replace me"
12        textField.translatesAutoresizingMaskIntoConstraints = false
13
14        let button = UIButton(type: .system)
15        button.setTitle("Select All", for: .normal)
16        button.addTarget(self, action: #selector(selectAllTapped), for: .touchUpInside)
17        button.translatesAutoresizingMaskIntoConstraints = false
18
19        view.addSubview(textField)
20        view.addSubview(button)
21
22        NSLayoutConstraint.activate([
23            textField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
24            textField.centerYAnchor.constraint(equalTo: view.centerYAnchor),
25            textField.widthAnchor.constraint(equalToConstant: 220),
26            button.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: 16),
27            button.centerXAnchor.constraint(equalTo: view.centerXAnchor)
28        ])
29    }
30
31    @objc private func selectAllTapped() {
32        textField.becomeFirstResponder()
33
34        if let range = textField.textRange(
35            from: textField.beginningOfDocument,
36            to: textField.endOfDocument
37        ) {
38            textField.selectedTextRange = range
39        }
40    }
41}

This is the standard UIKit pattern and works well in normal user-driven flows.

Selecting When Editing Begins

If you want the whole text selected automatically when the user enters the field, the right place is often the delegate callback.

swift
1import UIKit
2
3final class ViewController: UIViewController, UITextFieldDelegate {
4    let textField = UITextField()
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8        textField.delegate = self
9    }
10
11    func textFieldDidBeginEditing(_ textField: UITextField) {
12        DispatchQueue.main.async {
13            if let range = textField.textRange(
14                from: textField.beginningOfDocument,
15                to: textField.endOfDocument
16            ) {
17                textField.selectedTextRange = range
18            }
19        }
20    }
21}

The DispatchQueue.main.async is sometimes useful because it lets the responder transition complete before selection is applied.

Why Selection Sometimes Fails

Programmatic selection depends on timing and responder state. If the field is not active yet, UIKit may ignore the selection request or immediately replace it during editing setup.

That is why code that looks correct can fail when called:

  • too early in the view lifecycle
  • before the field is on screen
  • before the field becomes first responder

When in doubt, perform selection after becomeFirstResponder() and, if needed, on the next main-thread turn.

Select All Versus Cursor Placement

There is also a behavioral difference between putting the cursor at the end of the text and selecting the entire range. If you only call becomeFirstResponder(), UIKit will usually place the insertion point somewhere appropriate, but it will not automatically highlight everything. Full replacement behavior requires an actual range assignment.

That distinction is important in forms where you want the next keystroke to replace the existing value instead of appending to it.

Common Pitfalls

  • Setting selectedTextRange before the field becomes first responder.
  • Trying to select text before the field is actually visible and interactive.
  • Forgetting to check that the text range was created successfully.
  • Applying the selection too early in delegate flow and then wondering why UIKit overwrote it.
  • Assuming programmatic selection will work the same way for every custom text input control. This pattern is for UITextField.

Summary

  • To select all text in a UITextField, make it first responder and set selectedTextRange to the full document range.
  • 'beginningOfDocument and endOfDocument define the full selectable span.'
  • 'textFieldDidBeginEditing is a good place to auto-select when editing starts.'
  • If timing is unreliable, defer the selection with DispatchQueue.main.async.
  • Most failures happen because the field is not yet active when the selection is requested.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.