Class

UIText​Field

A UIText​Field object displays an editable text area in your interface. You use text fields to gather text-based input from the user using the onscreen keyboard. The keyboard is configurable for many different types of input such as plain text, emails, numbers, and so on. Text fields use the target-action mechanism and a delegate object to report changes made during the course of editing.

Overview

In addition to its basic text-editing behavior, you can add overlay views to a text field to display additional information and provide additional tappable controls. You might add custom overlay views for elements such as a bookmarks button or search icon. Text fields provide a built-in overlay view to clear the current text. The use of custom overlay views is optional.

After adding a text field to your interface, you configure it for use in your app. Configuration involves performing some or all of the following tasks:

  • Configure one or more targets and actions for the text field.

  • Configure the keyboard-related attributes of the text field.

  • Assign a delegate object to handle important tasks, such as:

    • Determining whether the user should be allowed to edit the text field’s contents.

    • Validating the text entered by the user.

    • Responding to taps in the keyboard’s return button.

    • Forwarding the user-entered text to other parts of your app.

  • Store a reference to the text field in one of your controller objects.

For information about the methods of the text field’s delegate object, see UIText​Field​Delegate.

Showing and Hiding the Keyboard

When a text field becomes first responder, the system automatically shows the keyboard and binds its input to the text field. A text field becomes the first responder automatically when the user taps it. You can also force a text field to become the first responder by calling its become​First​Responder() method. You might force a text field to become first responder when you require the user to enter some information.

You can ask the system to dismiss the keyboard by calling the resign​First​Responder() method of your text field. Usually, you dismiss the keyboard in response to specific interactions. For example, you might dismiss the keyboard when the user taps the keyboard’s return key. The system can also dismiss the keyboard in response to user actions. Specifically, the system dismisses the keyboard when the user taps a new control that does not support keyboard input.

The appearance and dismissal of the keyboard affect the editing state of the text field. When the keyboard appears, the text field enters the editing state and sends the appropriate notifications to its delegate. Similarly, when the text field resigns the first responder status, it leaves the editing state and notifies its delegate. For more information about the sequence of events that occur during editing, see Validating Text and Managing the Editing Process.

Configuring the Keyboard’s Appearance

You customize your text field’s keyboard using the properties of the UIText​Input​Traits protocol, which the UIText​Field class adopts. UIKit supports standard keyboards for the user’s current language and also supports specialized keyboards for entering numbers, URLs, email addresses, and other specific types of information. You use the properties of this protocol to adjust keyboard traits such as the following:

  • The type of keyboard to display

  • The autocapitalization behavior of the keyboard

  • The autocorrection behavior of the keyboard

  • The type of return key to display

For information about how to configure keyboard attributes in Interface Builder or in your code, see Table 2.

Responding to Keyboard-Related Notifications

Because the system manages the showing and hiding of the keyboard in response to responder changes, it posts the following notifications for tracking the keyboard-related changes:

Each notification contains a user​Info dictionary that includes the size of the keyboard. Because the keyboard can hide portions of your interface, you should use the size information to reposition your content on the screen. For content embedded in a scroll view, you can scroll the text field into view, as illustrated in Figure 2. In other cases, you can resize your main content view so that it is not covered by the keyboard.

Figure 2

Adjusting the position of a text field when the keyboard appears

For more information about managing keyboard interactions, see Text Programming Guide for iOS.

Formatting the Text in a Text Field

There are two types of formatting you can do to a text field’s text:

  • You can change the font, color, and style of the text using properties of this class. Alternatively, you can specify an NSAttributed​String for the text field’s content.

  • You can format the content of a text field using an Formatter object.

The font, text​Color, and text​Alignment properties, among others, affect the appearance of the text field’s string. Modifying these properties applies the specified characteristic to the entire string. To specify more granular formatting, specify the text field’s text using an NSAttributed​String object.

The UIText​Field class does not provide built-in support for formatting its string using an Formatter object, but you can use the text field’s delegate to format the content yourself. To do so, use the text field’s delegate methods to validate text and to format it appropriately. For example, use the text​Field(_:​should​Change​Characters​In:​replacement​String:​) method to validate and format text while the user is typing. For information about how to use formatter objects, see Data Formatting Guide.

Using Overlay Views to Edit Content

Overlay views are small views displayed on the left and right sides of the text view’s editable area. Typically, overlay views are image-based buttons that you set up as additional editing controls. For example, you might use an overlay view to implement a bookmarks button. To configure a button as an overlay view, specify an image for the button’s content and configure the target and action of the button to respond to taps.

Listing 1 shows how to add a button as the left overlay of a text field. In this case, the code creates a button and configure its size and contents. The left​View​Mode property specifies when your button is displayed. When the user taps the button, the button calls the configured action method, which in this case is a custom display​Bookmarks:​ method.

Listing 1

Adding an overlay view to a text field

UIButton* overlayButton = [UIButton buttonWithType:UIButtonTypeCustom];
[overlayButton setImage:[UIImage imageNamed:@"bookmark"] forState:UIControlStateNormal];
[overlayButton addTarget:self action:@selector(displayBookmarks:)
        forControlEvents:UIControlEventTouchUpInside];
overlayButton = CGRectMake(0, 0, 28, 28);
 
// Assign the overlay button to a stored text field
self.textField.leftView = overlayButton;
self.textField.leftViewMode = UITextFieldViewModeAlways;

When configuring overlay views, consider whether you want your text field to display the built-in clear button. The clear button provides the user with a convenient way to delete all of the text field’s text. This button is displayed in the right overlay position, but if you provide a custom right overlay view, use the right​View​Mode and clear​Button​Mode properties to define when your custom overlay should be displayed and when the clear button should be displayed.

Validating Text and Managing the Editing Process

A text field manages the editing of its text with the help of its delegate object. As the user interacts with a text field, the text field notifies its delegate and gives it a chance to control what is happening. You can use the delegate methods to prevent the user from starting or stopping the editing process or to validate text as it is typed. You can also use the delegate methods to perform related tasks, such as updating other parts of your interface based on the information typed by the user.

For more information about using the text field’s delegate to manage editing interactions, see UIText​Field​Delegate.

Interface Builder Attributes

Table 1 lists the attributes that you configure for text fields in Interface Builder.

Table 1

Text Field attributes

Attribute

Description

Text

The initial text displayed by the text field. You can specify the text as a plain string or as an attributed string. If you specify an attributed string, Interface Builder provides different options for editing the font, color, and formatting of the string.

Color

The color of the text field’s text. To set this attribute programmatically, use the text​Color property.

Font

The font of the text field’s text. To set this attribute programmatically, use the font property.

Alignment

The alignment of the text field’s text inside the editing area. This option is available only when formatting plain strings. To set this attribute programmatically, use the text​Alignment property.

Placeholder

The placeholder text displayed by the text field. When the text field’s string is empty, the text field displays this string instead, formatting the string so as to indicate that it is not the actual text. Typing any text into the text field hides this string. To set this attribute programmatically, use the placeholder property.

Background

The background image to display when the text field is enabled. This image is displayed behind the rest of the text field’s content. To set this attribute programmatically, use the background property.

Disabled

The background image to display when the text field is disabled. This image is displayed behind the rest of the text field’s content. To set this attribute programmatically, use the disabled​Background property.

Border Style

The visual style for the text field’s border. This attribute defines the visual border, if any, drawn around the editable text region. To set this attribute programatically, use the border​Style property.

Clear Button

The behavior of the clear button. The clear button is a built-in overlay view that the user taps to delete all of the text in a text field. Use this attribute to define when the clear button appears. To set this attribute programatically, use theclear​Button​Mode property.

Min Font Size

The minimum font size for the text field’s text. When the Adjust to Fit option is enabled, the text field automatically varies the font size to ensure maximum legibility of the text. You can use this attribute to specify the smallest font size that your consider appropriate for your text. To set this attribute programatically, use theminimum​Font​Size property.

Table 2 lists the keyboard-related attributes that you configure for text fields. This attributes correspond to properties of the UIText​Input​Traits protocol that the UIText​Field class adopts.

Table 2

Keyboard attributes

Attribute

Description

Capitalization

The automatic capitalization style to apply to typed text. This attribute determines at what time the Shift key is automatically pressed. You can access the value of this attribute programmatically using the text field’s autocapitalization​Type property.

Correction

The autocorrection behavior of the text field. This attribute determines whether autocorrection is enabled or disabled during typing. You can access the value of this attribute programmatically using the text field’s autocorrection​Type property.

Spell Checking

The spell checking behavior of the text field. This attribute determines whether spell checking is enabled or disabled during typing. You can access the value of this attribute programmatically using the text field’s spell​Checking​Type property.

Keyboard Type

The style of the text field’s keyboard. This property specifies the type of keyboard displayed when the text field is active. You can access the value of this attribute programmatically using the text field’s keyboard​Type property.

Appearance

The visual style applied to the text field’s keyboard. Use this property to specify a dark or light keyboard. You can access the value of this attribute programmatically using the text field’s keyboard​Appearance property.

Return Key

The type of return key to display on the keyboard. Use this property to configure the text and visual style applied to the keyboard’s return key. You can access the value of this attribute programmatically using the text field’s return​Key​Type property.

The return key is disabled by default and becomes enabled only when the user types some text into the text field. To respond to taps in the Return key, implement the text​Field​Should​Return(_:​) method in the delegate you assign to the text field.

For information about additional attributes you can configure for a text view, see UIControl.

Internationalization

The default language of the device affects the keyboard that pops up with the text field (including the return key). You do not need to do anything to enable this functionality; it is enabled by default. However, your text field should be able to handle input that comes from any language.

When using storyboards to build your interface, use Xcode’s base internationalization feature to configure the localizations your project supports. When you add a localization, Xcode creates a strings file for that localization. When configuring your interface programmatically, use the system’s built-in support for loading localized strings and resources. For more information about internationalizing your interface, see Internationalization and Localization Guide.

Accessibility

Text fields are accessible by default. The default accessibility traits for a button are User Interaction Enabled and Adjustable.

For more information about making iOS controls accessible, see the accessibility information in UIControl. For general information about making your interface accessible, see Accessibility Programming Guide for iOS.

State Preservation

When you assign a value to a text field’s restoration​Identifier property, it preserves the selected range of text, if any. During the next launch cycle, the text field attempts to restore that selection. If the selection range cannot be applied to the current text, no selection is made. For more information about how state preservation and restoration works, see App Programming Guide for iOS.

Symbols

Accessing the Text Attributes

var text:​ String?

The text displayed by the text field.

var attributed​Text:​ NSAttributed​String?

The styled text displayed by the text field.

var placeholder:​ String?

The string that is displayed when there is no other text in the text field.

var attributed​Placeholder:​ NSAttributed​String?

The styled string that is displayed when there is no other text in the text field.

var default​Text​Attributes:​ [String :​ Any]

The default attributes to apply to the text.

var font:​ UIFont?

The font of the text.

var text​Color:​ UIColor?

The color of the text.

var text​Alignment:​ NSText​Alignment

The technique to use for aligning the text.

var typing​Attributes:​ [String :​ Any]?

The attributes to apply to new text being entered by the user.

Sizing the Text Field’s Text

var adjusts​Font​Size​To​Fit​Width:​ Bool

A Boolean value indicating whether the font size should be reduced in order to fit the text string into the text field’s bounding rectangle.

var minimum​Font​Size:​ CGFloat

The size of the smallest permissible font with which to draw the text field’s text.

Managing the Editing Behavior

var is​Editing:​ Bool

A Boolean value indicating whether the text field is currently in edit mode.

var clears​On​Begin​Editing:​ Bool

A Boolean value indicating whether the text field removes old text when editing begins.

var clears​On​Insertion:​ Bool

A Boolean value indicating whether inserting text replaces the previous contents.

var allows​Editing​Text​Attributes:​ Bool

A Boolean value indicating whether the user may edit the attributes of the text in the text field.

Setting the View’s Background Appearance

var border​Style:​ UIText​Border​Style

The border style used by the text field.

var background:​ UIImage?

The image that represents the background appearance of the text field when it is enabled.

var disabled​Background:​ UIImage?

The image that represents the background appearance of the text field when it is disabled.

Managing Overlay Views

var clear​Button​Mode:​ UIText​Field​View​Mode

Controls when the standard clear button appears in the text field.

var left​View:​ UIView?

The overlay view displayed on the left (or leading) side of the text field.

var left​View​Mode:​ UIText​Field​View​Mode

Controls when the left overlay view appears in the text field.

var right​View:​ UIView?

The overlay view displayed on the right (or trailing) side of the text field.

var right​View​Mode:​ UIText​Field​View​Mode

Controls when the right overlay view appears in the text field.

Accessing the Delegate

Drawing and Positioning Overrides

func text​Rect(for​Bounds:​ CGRect)

Returns the drawing rectangle for the text field’s text.

func draw​Text(in:​ CGRect)

Draws the receiver’s text in the specified rectangle.

func placeholder​Rect(for​Bounds:​ CGRect)

Returns the drawing rectangle for the text field’s placeholder text

func draw​Placeholder(in:​ CGRect)

Draws the receiver’s placeholder text in the specified rectangle.

func border​Rect(for​Bounds:​ CGRect)

Returns the receiver’s border rectangle.

func editing​Rect(for​Bounds:​ CGRect)

Returns the rectangle in which editable text can be displayed.

func clear​Button​Rect(for​Bounds:​ CGRect)

Returns the drawing rectangle for the built-in clear button.

func left​View​Rect(for​Bounds:​ CGRect)

Returns the drawing rectangle of the receiver’s left overlay view.

func right​View​Rect(for​Bounds:​ CGRect)

Returns the drawing location of the receiver’s right overlay view.

Replacing the System Input Views

var input​View:​ UIView?

The custom input view to display when the text field becomes the first responder.

var input​Accessory​View:​ UIView?

The custom accessory view to display when the text field becomes the first responder

Constants

UIText​Border​Style

The type of border drawn around the text field.

UIText​Field​View​Mode

Defines the times at which overlay views appear in a text field.

Notifications

static let UIText​Field​Text​Did​Begin​Editing:​ NSNotification.Name

Notifies observers that an editing session began in a text field. The affected text field is stored in the object parameter of the notification. The user​Info dictionary is not used.

static let UIText​Field​Text​Did​Change:​ NSNotification.Name

Notifies observers that the text in a text field changed. The affected text field is stored in the object parameter of the notification.

static let UIText​Field​Text​Did​End​Editing:​ NSNotification.Name

Notifies observers that the editing session ended for a text field. The affected text field is stored in the object parameter of the notification. The user​Info dictionary is not used.