Text Label vs Text Field vs Text View

If you’re new to iOS development the differences between a text label, a text field or a text view can be confusing. Here’s a quick guide for when you’re not sure which to use.

Text Label

When you want to show some text, but don’t need the user to enter or edit the text your first choice should be a plain text label (UILabel):

Text Label

Options available in both Interface Builder and programmatically allow you to change properties such as the font, text alignment, and text color.

let label = UILabel()
label.text = "Hello World!"
label.font = UIFont.preferredFont(forTextStyle: .body)
label.adjustsFontForContentSizeCategory = true
label.textColor = .red
label.backgroundColor = .yellow
label.numberOfLines = 0

Notes:

Text Field

When you want the user to enter a single line of text use a text field (UITextField):

Text Field

let textField = UITextField()
textField.placeholder = "Enter your password"
textField.delegate = self // UITextFieldDelegate

Like a text label, you can set the font, text color, alignment, and other properties. A text field also supports the UITextInputTraits protocol which allows you to control the keyboard type and appearance, auto-capitalization and correction, the return key, spell-checking and secure-text entry:

Text input traits

textField.textContentType = .password
textField.isSecureTextEntry = true

Notes:

Text View

When you want to the user to enter more than one line of text use a text view (UITextView):

Text View

let textView = UITextView()
textView.text = "Hello World"

A text view supports UITextInputTraits like a text field, but the text in a text view can also be editable, scrollable or selectable. A text view is scrollable by default. You can disable scrolling in the scroll view section of the attributes inspector in Interface Builder:

Scroll View

Or if you prefer in code:

textView.isScrollEnabled = false

Note: A text view does not have an intrinsic content size when scrolling is enabled.

Even if you do not want a text view to be editable or scrollable you might still use it to display text instead of a text label to allow the user to select, copy and lookup text:

Copy, lookup and share selected text

Note: A text view is selectable and editable by default. Change the defaults in Interface Builder or in code:

Text view selectable and editable

textView.isSelectable = false
textView.isEditable = false

Summary

Read More

See the following WWDC session for a flowchart to help you choose the right text control:

If you want to find out more about using text labels, text fields, and text views to build adaptive layouts see my book on Auto Layout:

Never Miss A Post

Sign up to get my iOS posts and news direct to your inbox and I'll also send you a PDF of my WWDC Viewing Guide

    Unsubscribe at any time. See privacy policy.

    Archives Categories