1. Home
  2. Docs
  3. iOS
  4. UI Controls
  5. Text Views (UITextView)

Text Views (UITextView)

What is UITextView?

UITextView is a multiline text input field in UIKit that allows users to view and edit large amounts of text. Unlike UITextField, which is single-line, UITextView supports multiple lines and rich text formatting.


1. Creating a UITextView

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

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

2. Adding UITextView via Storyboard

  1. Open Main.storyboard in Xcode.
  2. Drag and drop a UITextView from the Object Library onto the view.
  3. Resize and position it as needed.
  4. Customize its appearance using the Attributes Inspector.
  5. Create an IBOutlet in ViewController.swift: @IBOutlet weak var myTextView: UITextView!
  6. Modify properties in viewDidLoad(): override func viewDidLoad() { super.viewDidLoad() myTextView.text = "Enter your text here..." myTextView.font = UIFont.systemFont(ofSize: 16) myTextView.textColor = UIColor.darkGray myTextView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2) }

3. Creating UITextView Programmatically

import UIKit

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

        // Create UITextView
        let myTextView = UITextView()
        myTextView.text = "Type something here..."
        myTextView.font = UIFont.systemFont(ofSize: 16)
        myTextView.textColor = UIColor.darkGray
        myTextView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
        myTextView.layer.cornerRadius = 10
        myTextView.layer.borderWidth = 1
        myTextView.layer.borderColor = UIColor.gray.cgColor

        // Enable Auto Layout
        myTextView.translatesAutoresizingMaskIntoConstraints = false

        // Set Delegate
        myTextView.delegate = self

        // Add to View
        view.addSubview(myTextView)

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

Explanation:

  • Creates a UITextView with a placeholder text, font, border, and rounded corners.
  • Uses Auto Layout to position it in the center.
  • Implements UITextViewDelegate for event handling.

4. UITextView Customization

4.1 Changing Text, Font, and Color

myTextView.text = "Welcome to iOS Development!"
myTextView.textColor = .black
myTextView.font = UIFont.systemFont(ofSize: 18, weight: .medium)

4.2 Changing Background Color & Border

myTextView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
myTextView.layer.borderWidth = 1
myTextView.layer.borderColor = UIColor.gray.cgColor

4.3 Making Text Editable or Read-Only

myTextView.isEditable = false  // Prevents editing
myTextView.isSelectable = false // Prevents text selection

4.4 Changing Text Alignment

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

4.5 Auto-Capitalization & Auto-Correction

myTextView.autocapitalizationType = .sentences  // .none, .words, .allCharacters
myTextView.autocorrectionType = .no

5. UITextView Placeholder Effect

Unlike UITextField, UITextView does not have a built-in placeholder. To add a placeholder effect:

func textViewDidBeginEditing(_ textView: UITextView) {
    if textView.text == "Enter your message..." {
        textView.text = ""
        textView.textColor = UIColor.black
    }
}

func textViewDidEndEditing(_ textView: UITextView) {
    if textView.text.isEmpty {
        textView.text = "Enter your message..."
        textView.textColor = UIColor.lightGray
    }
}

Explanation:

  • When editing begins, it clears the placeholder text.
  • When editing ends, if empty, it restores the placeholder text.

6. UITextView Keyboard & Scrolling

6.1 Handling Keyboard Return Key

func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
    textView.resignFirstResponder() // Dismiss keyboard
    return true
}

6.2 Dismissing Keyboard on Tap Outside

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

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

6.3 Adjusting View When Keyboard Appears

To prevent the keyboard from covering the UITextView, use NotificationCenter:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

@objc func keyboardWillShow(notification: Notification) {
    if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
        view.frame.origin.y = -keyboardFrame.height / 2
    }
}

@objc func keyboardWillHide(notification: Notification) {
    view.frame.origin.y = 0
}

7. UITextView with Links (Detecting URLs & Phone Numbers)

To automatically detect links, phone numbers, and emails, enable dataDetectorTypes:

myTextView.dataDetectorTypes = [.link, .phoneNumber, .address]
myTextView.isEditable = false // Prevents user editing

✅ This makes phone numbers clickable and opens links in Safari.


8. UITextView in a ScrollView

If you want a UITextView inside a UIScrollView:

let scrollView = UIScrollView()
let textView = UITextView()
textView.text = "Long text goes here..."
scrollView.addSubview(textView)
view.addSubview(scrollView)

✅ This ensures smooth scrolling when the text content is large.


9. UITextView Example: Notes App

let notesTextView = UITextView()
notesTextView.text = "Write your notes here..."
notesTextView.font = UIFont.systemFont(ofSize: 18)
notesTextView.backgroundColor = UIColor.systemYellow.withAlphaComponent(0.2)
notesTextView.layer.cornerRadius = 10
notesTextView.translatesAutoresizingMaskIntoConstraints = false

view.addSubview(notesTextView)

NSLayoutConstraint.activate([
    notesTextView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
    notesTextView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
    notesTextView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
    notesTextView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20)
])

✅ This creates a simple note-taking app.


10. Summary

FeatureCode Example
Set TextmyTextView.text = "Hello World!"
Set Font & ColormyTextView.font = UIFont.systemFont(ofSize: 16)
Disable EditingmyTextView.isEditable = false
Detect Links & PhonesmyTextView.dataDetectorTypes = [.link, .phoneNumber]
Text AlignmentmyTextView.textAlignment = .center
Dismiss Keyboardview.endEditing(true)

Conclusion

  • UITextView is ideal for large text inputs (comments, descriptions, notes).
  • It supports rich text, scrolling, and link detection.
  • Use UITextViewDelegate for handling input events.

Would you like a rich text editor example using UITextView? 🚀