UIAlertController
UITextField
iOS development
Swift programming
user input

How to get input value from a UIAlertController text field?

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

UIAlertController is a convenient way to collect a small piece of user input without building a custom screen. The usual pattern is simple: create the alert, add one or more text fields, and read the text inside the action handler after the user taps a button. The important detail is that the text lives in the alert controller’s textFields array, not in the action itself.

Add a Text Field and Read Its Value

Text fields are only supported when the alert controller uses .alert style. You add the field before presenting the alert, then pull the value out in the submit action.

swift
1import UIKit
2
3final class ProfileViewController: UIViewController {
4    @IBOutlet private weak var nameLabel: UILabel!
5
6    @IBAction private func renameTapped(_ sender: UIButton) {
7        let alert = UIAlertController(
8            title: "Rename profile",
9            message: "Enter a new display name.",
10            preferredStyle: .alert
11        )
12
13        alert.addTextField { textField in
14            textField.placeholder = "Display name"
15            textField.text = self.nameLabel.text
16            textField.clearButtonMode = .whileEditing
17            textField.autocapitalizationType = .words
18        }
19
20        let saveAction = UIAlertAction(title: "Save", style: .default) { [weak self, weak alert] _ in
21            let rawText = alert?.textFields?.first?.text ?? ""
22            let name = rawText.trimmingCharacters(in: .whitespacesAndNewlines)
23
24            guard !name.isEmpty else {
25                self?.showValidationError()
26                return
27            }
28
29            self?.nameLabel.text = name
30        }
31
32        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
33        alert.addAction(saveAction)
34
35        present(alert, animated: true)
36    }
37
38    private func showValidationError() {
39        let errorAlert = UIAlertController(
40            title: "Invalid name",
41            message: "The display name cannot be empty.",
42            preferredStyle: .alert
43        )
44        errorAlert.addAction(UIAlertAction(title: "OK", style: .default))
45        present(errorAlert, animated: true)
46    }
47}

The key line is alert?.textFields?.first?.text. That is where the entered value is stored when the action handler runs.

Working with More Than One Field

If the alert has multiple inputs, access them by index in the textFields array. Add the fields in a predictable order and read them back in the same order.

swift
1let alert = UIAlertController(
2    title: "Sign in",
3    message: "Enter your email and one-time code.",
4    preferredStyle: .alert
5)
6
7alert.addTextField { $0.placeholder = "Email" }
8alert.addTextField {
9    $0.placeholder = "Code"
10    $0.keyboardType = .numberPad
11}
12
13let submit = UIAlertAction(title: "Continue", style: .default) { [weak alert] _ in
14    let email = alert?.textFields?[0].text ?? ""
15    let code = alert?.textFields?[1].text ?? ""
16    print("email:", email, "code:", code)
17}
18
19alert.addAction(submit)

This pattern is fine for one or two short values. If the interaction becomes more complex, a dedicated view controller is usually easier to validate, test, and maintain.

Validation and Presentation Details

Most bugs around alert input are not about reading the text. They come from validation and presentation timing.

You should usually trim whitespace, reject empty values, and make sure the alert is presented on the main thread. In UIKit event handlers you are already on the main thread, but if you trigger the alert from an async callback, wrap presentation in DispatchQueue.main.async.

It is also common to prefill the text field with the current value so the alert behaves like an edit dialog rather than a blank prompt. That makes the UI feel more deliberate and reduces accidental data loss.

Common Pitfalls

One mistake is trying to read the text immediately after calling addTextField. At that point, the user has not entered anything yet. Read it inside the action handler that runs after the tap.

Another mistake is using .actionSheet and expecting text fields to appear. Text fields are supported on .alert, not on action sheets.

Developers also sometimes force-unwrap the first text field. That works until the alert configuration changes. Optional access with a sensible fallback is safer.

Finally, avoid treating an alert as a full form. If you need several fields, inline validation, or complex keyboard behavior, build a custom screen instead of stretching UIAlertController beyond its intended use.

Summary

  • Add text fields with addTextField before presenting the alert.
  • Read the user’s input from alert.textFields inside the action handler.
  • Use .alert style, not .actionSheet, when you need text entry.
  • Trim and validate the value before using it in your UI or network request.
  • For larger forms, switch to a dedicated view controller instead of overloading an alert.

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.