UITextField — What It Is, Input Field Setup, and How It Works

Author: IT Sectr Published: 2026-07-06 Reading time: 8 min

UITextField is a standard UIKit component for single-line text input in iOS, inheriting from UIControl and supporting a wide range of keyboard modes. According to Apple Developer documentation (2025), UITextField provides the UITextFieldDelegate with callbacks shouldBeginEditing, shouldChangeCharactersInRange, and shouldReturn. Unlike UITextView, UITextField limits input to a single line and supports secureTextEntry, leftView, and rightView for custom controls. This is the main element for authorization forms, search, registration, and data input in iOS applications.

Key Takeaways

  • UITextField — single-line UIKit input field with delegate support and custom keyboards
  • UIKeyboardType — 12 keyboard types: numberPad, emailAddress, URL, phonePad, and others
  • UITextFieldDelegate — managing the input lifecycle through shouldBegin/End/Change callbacks
  • Secure Text Entry — password input mode with character replacement via isSecureTextEntry
  • Left/Right View — custom icons and buttons inside the input field for UX improvements

What Is UITextField

UITextField is a UIKit framework class designed for single-line text input by the user. The class inherits from UIControl, allowing subscription to input events via the target-action mechanism: addTarget(self, action: Selector("textChanged:"), for: editingChanged). UITextField displays a border (borderStyle), placeholder text when the field is empty, a clear button (clearButtonMode), and can contain left/right accessory views. The field automatically shows/hides the keyboard when gaining/losing focus via becomeFirstResponder and resignFirstResponder. The field size is determined by intrinsicContentSize based on font and border style. To create a UITextField in Interface Builder (Storyboard/XIB), use the Object Library; programmatically, use the initializer UITextField(frame: CGRect). The class is fully compatible with modern iOS architecture: Combine publishers, @Published in SwiftUI via UIViewRepresentable, and Diffable Data Source for forms.

UIKeyboardType Keyboard Types

UITextField supports 12 keyboard types via the keyboardType property. Each type optimizes the character set for a specific input scenario. UIKeyboardType.default — standard QWERTY keyboard. UIKeyboardType.numberPad — digits only without additional symbols (ideal for PIN codes and phone numbers). UIKeyboardType.emailAddress — keyboard with @ and dot on the main layer. UIKeyboardType.URL — keyboard with .com, /, and dot on the main layer. UIKeyboardType.phonePad — numeric keypad with +, *, # for entering phone numbers. UIKeyboardType.decimalPad — digits with a decimal point for entering prices. UIKeyboardType.webSearch — keyboard with a Go button optimized for search queries. UIKeyboardType.asciiCapable — ASCII characters only for Latin text. The keyboard appears when becomeFirstResponder is called and hides when resignFirstResponder is called. The keyboard type can be changed dynamically during editing.

TypeScenarioFeatures
defaultGeneral text inputStandard QWERTY
numberPadPIN, codeDigits 0-9 only
emailAddressEmail@ and dot on main layer
URLWeb address.com, /, dot on main
phonePadPhoneDigits, +, *, #
decimalPadPrice, numberDigits + decimal point

UITextFieldDelegate and Its Methods

UITextFieldDelegate is a protocol that defines the behavior of the text field at different stages of input. Key methods: textFieldShouldBeginEditing(textField) — returns a Bool allowing or denying the start of editing; textFieldDidBeginEditing — called after the keyboard appears; textFieldShouldEndEditing — checks whether editing can be completed (if false, the field does not lose focus); textFieldDidEndEditing — called after the keyboard hides; textFieldShouldChangeCharactersInRange — called on each character input, allows filtering input (only one character allowed, if false is returned — the character is not added); textFieldShouldReturn — called when Return/Go/Next/Search is pressed, used to move to the next field. The delegate is not Optional: all methods have a default implementation, but for custom behavior you need to override the corresponding method.

Focus Management via shouldReturn

The shouldReturn method is the standard pattern for navigating between form fields. Implementation: textFieldShouldReturn(textField) — check which textField triggered the event and move focus to the next field via becomeFirstResponder(). If it is the last field, call resignFirstResponder() to hide the keyboard. Use IBOutlet collection or separate IBOutlets for each field to store field references.

Secure Text Entry and Custom Left/Right Views

isSecureTextEntry — a UITextField property that, when true, replaces entered characters with bullets (•) and blocks text copying via UIMenuController. Used for password fields, PIN codes, CVV. When switching between secure mode and plain text (show/hide password), set textField.isSecureTextEntry.toggle(). Important: when isSecureTextEntry changes, the field text resets — save it beforehand. LeftView and RightView are custom UIViews displayed inside the input field on the left or right. Typical usage: a search icon in leftView, a "Clear" button in rightView. Configuration: textField.leftViewMode = always (always) or whileEditing (only while editing). Left/right views are automatically positioned inside the text field considering padding. The view size is set via bounds or Auto Layout.

swift
import UIKit

class LoginViewController: UIViewController {
    let passwordField = UITextField()

    override func viewDidLoad() {
        super.viewDidLoad()
        passwordField.isSecureTextEntry = true
        passwordField.placeholder = "Password"
        passwordField.keyboardType = .asciiCapable
        passwordField.delegate = self

        // Custom show/hide password button
        let showButton = UIButton(type: .system)
        showButton.setTitle("Show", for: .normal)
        showButton.addTarget(self, action: #selector(togglePasswordVisibility),
                       for: .touchUpInside)
        passwordField.rightView = showButton
        passwordField.rightViewMode = .always
    }

    @objc func togglePasswordVisibility() {
        passwordField.isSecureTextEntry.toggle()
    }
}

Configuring UITextInputTraits

UITextInputTraits is a protocol that defines the visual and behavioral appearance of the keyboard for UITextField. Key properties: autocorrectionType (.default, .no, .yes) — enables or disables text autocorrection; autocapitalizationType (.none, .words, .sentences, .allCharacters) — automatic Caps Lock for the first character; spellCheckingType — spell checking; returnKeyType (.done, .go, .next, .search, .send, .continue, .join, .route, .emergencyCall) — the Return button text on the keyboard; enablesReturnKeyAutomatically — automatic disabling of the Return button when the field is empty. For name input fields, use autocapitalizationType = .words; for email, use autocorrectionType = .no; for URL, use keyboardType = .URL + autocapitalizationType = .none. Traits are configured after field initialization before it is displayed. Changing traits dynamically updates the keyboard on its next appearance.

Return Key Type and Form Navigation

Return Key Type defines the button text on the keyboard: Next — move to the next field, Done — complete input, Search — start search, Send — submit the form, Continue — continue filling. Combined with the shouldReturn delegate method, returnKeyType enables a natural UX: the user fills in fields, pressing Next to move to the next, and Done to submit on the last field. For button text customization, use UIButtonConfiguration in iOS 15+.

Placeholder, Formatting, and Input Mask

UITextField Placeholder is the text displayed in gray when the field is empty. Configuration: textField.placeholder = "Enter email". For customizing placeholder color and font, use attributedPlaceholder with NSAttributedString. Input mask is implemented through the delegate method shouldChangeCharactersInRange — supports phone number, date, credit card, and SNILS formats. The input mask allows separating display from value: the user sees formatted text (e.g., +7 (999) 999-99-99), while the model stores "79999999999". Example implementation: store the mask as a string with X characters for replacement; on each input, form the formatted string and return false in shouldChangeCharactersInRange, replacing the field text via textField.text = formattedText. For numbers, use NumberFormatter and the decimal keyboardType.

swift
extension LoginViewController: UITextFieldDelegate {
    func textFieldShouldReturn(
        textField: UITextField
    ) -> Bool {
        if textField == emailField {
            passwordField.becomeFirstResponder()
        } else if textField == passwordField {
            textField.resignFirstResponder()
            loginTapped()
        }
        return true
    }

    func textField(
        textField: UITextField,
        shouldChangeCharactersIn range: NSRange,
        replacementString string: String
    ) -> Bool {
        // Block spaces in email
        if textField == emailField && string == " " {
            return false
        }
        // Password length limit
        if textField == passwordField {
            let newLength = (textField.text?.count ?? 0) +
                string.count - range.length
            return newLength <= 32
        }
        return true
    }
}

Code Examples: Validation and Form

Let's look at a complete example of implementing a login form with UITextField, email validation, and visual feedback. The form contains two fields: emailField (emailAddress keyboard, no autocorrection) and passwordField (secureTextEntry). Validation is performed in shouldChangeCharactersInRange and additionally when the Login button is pressed. For visual feedback: red border (layer.borderColor) on error, green — on successful validation. Border reset when editing begins in textFieldDidBeginEditing.

Email Validation with Regular Expression

Email validation is performed using NSPredicate with the format "SELF MATCHES %@" and a regular expression for basic format checking. Real email existence checking should be done on the server. For advanced validation, use the SwiftValidators library or Combine publishers. Example: NSPredicate(format: "SELF MATCHES [c] %@", emailRegex).evaluate(with: email). The field border updates via an animation block for a smooth transition.

swift
func validateEmail(textField: UITextField) {
    guard let text = textField.text, !text.isEmpty else {
        textField.layer.borderColor = UIColor.clear.cgColor
        return
    }

    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.\\p{L}{2,}"
    let predicate = NSPredicate(format: "SELF MATCHES [c] %@", emailRegex)
    let isValid = predicate.evaluate(with: text)

    UIView.animate(withDuration: 0.2) {
        textField.layer.borderColor = isValid
            ? UIColor.systemGreen.cgColor
            : UIColor.systemRed.cgColor
        textField.layer.borderWidth = 1.0
        textField.layer.cornerRadius = 6.0
    }
}

Frequently Asked Questions

How to limit the number of characters in UITextField?

Use the delegate method shouldChangeCharactersInRange. Calculate the new text length as existingText.count + newText.count - range.length and return false if the limit is exceeded. Alternatively: subscribe to the editingChanged event via addTarget and truncate the text using textField.text = String(text.prefix(maxLength)).

Why is UITextField not responding to touch?

Check: isUserInteractionEnabled = true (default), the delegate does not return false in shouldBeginEditing. If the field is inside a UIScrollView, disable delaysContentTouches. If the field is in a modal controller, check that it is not blocking touches. For SwiftUI UIViewRepresentable, check that the field correctly becomes firstResponder via DispatchQueue.main.async.

How to dismiss the keyboard when tapping outside UITextField?

Add a UITapGestureRecognizer on self.view or scrollView with a target-action that calls view.endEditing(true). Alternative: textField.resignFirstResponder() to dismiss the keyboard for a specific field. Implement touchesBegan in UIViewController or use the IQKeyboardManager library for automatic keyboard management. Remember to disable cancelsTouchesInView for proper button behavior.

How to change UITextField text color and font?

Text color: textField.textColor = UIColor.label. Font: textField.font = UIFont.systemFont(ofSize: 16, weight: .regular). Placeholder color: textField.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [.foregroundColor: UIColor.secondaryLabel]).

How to make UITextField read-only?

Three ways: isEnabled = false (changes appearance), isUserInteractionEnabled = false (preserves visual style), or return false in textFieldShouldBeginEditing delegate. The third method is preferred — it blocks input without changing the visual style. For programmatically setting text in read-only mode, use the delegate.

Summary

  • UITextField — single-line UIKit input field inheriting from UIControl with delegate management
  • UIKeyboardType — 12 keyboard types for different scenarios: email, URL, numberPad, phonePad
  • UITextFieldDelegate — protocol with shouldBegin/End/Change/Return methods for input management
  • Secure Text Entry — password mode via isSecureTextEntry with character replacement by bullets
  • Left/Right View — custom elements inside the field (icons, buttons) with always/whileEditing modes
  • Return Key Type — Return button configuration: Next, Done, Search, Send for form navigation
  • Validation — via shouldChangeCharactersInRange with regex and visual feedback through border
  • Placeholder is configured via attributedPlaceholder with NSAttributedString for custom styling

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

Discuss the project

Read also