1. Home
  2. Docs
  3. iOS
  4. UI Controls
  5. Text Fields (UITextField)

Text Fields (UITextField)

What is UITextField?

UITextField is a UI element in UIKit that allows users to enter and edit text. It is commonly used for forms, login screens, search bars, and input fields in iOS apps.


1. Creating a UITextField

There are two ways to add a UITextField in iOS development:

  1. Using Storyboard (Interface Builder)
  2. Programmatically in Swift

2. Adding UITextField via Storyboard

  1. Open Main.storyboard in Xcode.
  2. Drag and drop a UITextField from the Object Library onto the view.
  3. Customize its appearance using the Attributes Inspector (placeholder, text color, keyboard type, border style).
  4. Create an IBOutlet in the ViewController: @IBOutlet weak var myTextField: UITextField!
  5. Modify properties in viewDidLoad(): override func viewDidLoad() { super.viewDidLoad() myTextField.placeholder = "Enter your name" myTextField.borderStyle = .roundedRect myTextField.textColor = .darkGray }

3. Creating UITextField Programmatically

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Create UITextField
        let myTextField = UITextField()
        myTextField.placeholder = "Enter your email"
        myTextField.borderStyle = .roundedRect
        myTextField.textColor = .black
        myTextField.font = UIFont.systemFont(ofSize: 16)
        myTextField.keyboardType = .emailAddress
        myTextField.returnKeyType = .done

        // Enable Auto Layout
        myTextField.translatesAutoresizingMaskIntoConstraints = false

        // Set Delegate
        myTextField.delegate = self

        // Add to View
        view.addSubview(myTextField)

        // Set Constraints
        NSLayoutConstraint.activate([
            myTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myTextField.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            myTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            myTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            myTextField.heightAnchor.constraint(equalToConstant: 40)
        ])
    }
}

Explanation:

  • Creates a UITextField with a placeholder, border, text color, and keyboard type.
  • Uses Auto Layout to position it in the center.
  • Implements UITextFieldDelegate for event handling.

4. UITextField Customization

4.1 Changing Placeholder Text & Color

myTextField.placeholder = "Enter your name"
myTextField.attributedPlaceholder = NSAttributedString(
    string: "Enter your name",
    attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray]
)

4.2 Changing Text Color & Font

myTextField.textColor = .black
myTextField.font = UIFont.systemFont(ofSize: 18, weight: .medium)

4.3 Setting Border Style

myTextField.borderStyle = .roundedRect  // .none, .line, .bezel, .roundedRect

4.4 Adding a Background Color

myTextField.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)

4.5 Setting Text Alignment

myTextField.textAlignment = .center  // .left, .right, .justified

4.6 Making Text Secure (For Passwords)

myTextField.isSecureTextEntry = true

5. UITextField Keyboard Settings

5.1 Changing Keyboard Type

myTextField.keyboardType = .emailAddress  // .default, .numberPad, .decimalPad, .phonePad, .emailAddress

5.2 Changing Return Key Type

myTextField.returnKeyType = .done  // .next, .go, .search, .send

5.3 Enabling Auto-Capitalization & Auto-Correction

myTextField.autocapitalizationType = .words  // .none, .sentences, .words, .allCharacters
myTextField.autocorrectionType = .no  // .default, .no, .yes

6. Handling UITextField Events (Using Delegates)

To handle events like pressing the Return key, we use UITextFieldDelegate.

6.1 Dismissing the Keyboard on Return Key Press

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder() // Hides the keyboard
    return true
}

6.2 Detecting When Editing Begins

func textFieldDidBeginEditing(_ textField: UITextField) {
    print("User started typing...")
}

6.3 Detecting When Editing Ends

func textFieldDidEndEditing(_ textField: UITextField) {
    print("User stopped typing.")
}

6.4 Restricting Input Characters (Example: Max Length 10)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentText = textField.text ?? ""
    let updatedText = (currentText as NSString).replacingCharacters(in: range, with: string)
    return updatedText.count <= 10  // Limit to 10 characters
}

7. Adding an Icon to UITextField

To add an icon inside the UITextField, use a UIImageView as a leftView:

let iconImage = UIImageView(image: UIImage(systemName: "person.fill"))
iconImage.tintColor = .gray
iconImage.contentMode = .scaleAspectFit
iconImage.frame = CGRect(x: 10, y: 0, width: 20, height: 20)

myTextField.leftView = iconImage
myTextField.leftViewMode = .always  // .never, .whileEditing, .always

8. Dismissing Keyboard When Tapping Outside

To dismiss the keyboard when the user taps outside the UITextField, add this to viewDidLoad():

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tapGesture)

@objc func dismissKeyboard() {
    view.endEditing(true)  // Hides the keyboard
}

9. UITextField in a Login Form Example

let emailField = UITextField()
emailField.placeholder = "Enter your email"
emailField.borderStyle = .roundedRect
emailField.keyboardType = .emailAddress

let passwordField = UITextField()
passwordField.placeholder = "Enter your password"
passwordField.borderStyle = .roundedRect
passwordField.isSecureTextEntry = true

let stackView = UIStackView(arrangedSubviews: [emailField, passwordField])
stackView.axis = .vertical
stackView.spacing = 10

view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
    stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
    stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20)
])

10. Summary

FeatureCode Example
Set PlaceholdermyTextField.placeholder = "Enter your name"
Set Text ColormyTextField.textColor = .black
Set Border StylemyTextField.borderStyle = .roundedRect
Secure Text (Password)myTextField.isSecureTextEntry = true
Keyboard Type (Email)myTextField.keyboardType = .emailAddress
Disable Auto-CorrectionmyTextField.autocorrectionType = .no
Handle Return Keyfunc textFieldShouldReturn(_:) -> Bool { textField.resignFirstResponder() }

Conclusion

  • UITextField is essential for user input in iOS apps.
  • Supports customization, keyboard settings, icons, and event handling.
  • Use UITextFieldDelegate for better control over user input.

Would you like help integrating UITextField into a complete login form? 🚀