Skip to content

UITextView ​

UITextView represents an area where the user can type multiple lines of text. When the user taps it, the system keyboard appears; pressing Return inserts a line break instead of ending input. The app reads the full content from text, reads the cursor position and the selected range from selectedRange, and learns through events when the content changes, the cursor moves, and input begins and ends.

A text view is a scroll view: when the content is taller than the view itself, it scrolls vertically, and it has all the properties and events of a scroll view. Once isScrollEnabled is set to false, it no longer scrolls; instead it asks to be as tall as its lines of text. It is not a control: it has no isEnabled and none of the 16 control events. For single-line input, use UITextField.

Compared with a text field:

UITextFieldUITextView
LinesOneMultiple; Return inserts a line break
SuperclassControlScroll view
Content changedinput eventinput event
Input begins, endsfocus, blurfocus, blur
Pressing ReturnFires returnInserts a line break; no event
Placeholder textplaceholder propertyNone; overlay a label yourself
BorderborderStyle has four stylesNo usable border style; use a background color and corner radius
Intercepting before a changeCancelable events such as beforeinputCancelable events such as beforeinput
Tapping a link in attributed textNonelinkclick event
Cursor and selected rangeselectedRangeselectedRange
Cursor or selection movedselectionchange eventselectionchange event

The nine keyboard settings (keyboardType, textContentType, and so on) are the same on both.

Behavior marked "measured" in this set of pages was measured with a small program without UI in the simulator (iPhone Air, iOS 27.2). What appears on screen and the behavior of a real keyboard are marked "not verified in the simulator". On the four event pages beforefocus, beforeinput, beforeblur, and linkclick, "measured" means measured on a device (iPhone 14, iOS 27.2), and what wasn't measured is marked "not verified on a device".

Inheritance: EventTarget → NSObject → UIResponder → UIView → UIScrollView → UITextView

Two classes used with it: NSRange represents a range of text, and NSTextContainer represents the area where text is laid out.

For placeholder text, a text view that grows with its content, and dismissing the keyboard, see the guide Building a multiline text view.

Constructor ​

UITextView()

Creates a text view. It has no content, no font set, and a size of 0.

Instance properties ​

Also inherits properties from UIScrollView and UIView. Inherited properties commonly used with text views are isScrollEnabled, keyboardDismissMode, contentOffset, backgroundColor, and isFirstResponder.

Content:

PropertyDescription
textThe full content
attributedTextThe content with styles
hasText read-onlyWhether there is any content
clearsOnInsertionWhether inserting text replaces the whole content
allowsEditingTextAttributesWhether the user can change text styles
dataDetectorTypesWhich kinds of content become tappable links

Appearance:

PropertyDescription
fontThe font of the text
textColorThe color of the text
textAlignmentWhich side the text aligns to
textContainerInsetHow far the text is from the four edges
textContainer read-onlyThe area where text is laid out
usesStandardTextScalingWhether text is scaled by the standard ratio

Behavior:

PropertyDescription
isEditableWhether the user can change the content
isSelectableWhether the user can select text
selectedRangeThe selected range, or the cursor position
markedTextRange read-onlyThe stretch an input method is still composing, or null when not composing
isFindInteractionEnabledWhether system find and replace is turned on
isWritingToolsActive read-onlyWhether Writing Tools is currently working
writingToolsBehaviorHow much Writing Tools can do
allowedWritingToolsResultOptionsWhich kinds of content Writing Tools can write back

Keyboard:

PropertyDescription
keyboardTypeWhich keyboard appears
returnKeyTypeWhat the Return key says
keyboardAppearanceLight or dark keyboard
enablesReturnKeyAutomaticallyWhether the Return key is dimmed when there is no content
isSecureTextEntryPassword-style input
autocapitalizationTypeRules for automatic capitalization
autocorrectionTypeWhether autocorrection is on
spellCheckingTypeWhether spelling is checked
textContentTypeWhat kind of content goes here, used for AutoFill
smartQuotesTypeWhether straight quotes become curly quotes
smartDashesTypeWhether consecutive hyphens become a dash
smartInsertDeleteTypeWhether spaces are adjusted automatically on paste and delete
inlinePredictionTypeWhether predicted text is shown after the cursor
mathExpressionCompletionTypeWhether math expressions are evaluated automatically
allowsNumberPadPopoverWhether the number pad may appear as a popover
inputAccessoryViewA view attached above the keyboard when it appears
inputViewA view that appears instead of the system keyboard

Instance methods ​

Also inherits methods from UIScrollView and UIView. Inherited methods commonly used with text views are becomeFirstResponder() and resignFirstResponder(); see focus on UITextField.

MethodDescription
insertText()Inserts text at the cursor as if the user typed it
deleteBackward()Deletes as if the user pressed the Delete key
scrollRangeToVisible()Scrolls until a range of text is visible

Events ​

Listen with addEventListener(). A text view has eight events of its own, in two groups.

Notifications after the content, focus, or selection changed:

EventWhen it fires
focusIt becomes first responder and input begins
inputUser input changed the content, or code called insertText() or deleteBackward()
selectionchangeThe selection or cursor position changed
blurIt is no longer first responder and input ends

Events where the system asks on the spot whether to proceed; calling preventDefault() in a listener means no:

EventWhen it fires
beforefocusInput is about to begin. Canceling keeps it from entering editing
beforeinputUser input is about to change the content. Canceling stops the change
beforeblurInput is about to end. Canceling keeps the focus
linkclickThe user tapped a link in the attributed text. Canceling keeps it from opening

Inherited events:

EventWhen it fires
scroll and othersThe eight scroll view events, inherited from UIScrollView
traitchangeThe traits changed; inherited from UIView

Rules shared by the four notifications focus, input, selectionchange, and blur:

  • The event object's type is the event name and its target is the text view. The event object carries neither the content nor what changed. Read the content from text and the cursor from selectedRange.
  • They can't be canceled; preventDefault() has no effect. To block a character from being entered, use beforeinput.
  • Callbacks don't run synchronously at the moment the event happens; they run a little later. See when callbacks run. On the line after calling insertText(), the callback hasn't run yet.
  • An exception thrown in a callback doesn't affect the text view, and other callbacks for the same event still run. The exception fires error on application; if no listener cancels it, the console logs a message starting with Uncaught.
  • There is no cost when there are no listeners.
  • Scroll view events can be listened to alongside these eight without interfering with each other (measured).
  • Listening to any other name doesn't throw: it is treated as a custom event and fires only when you dispatch it yourself with dispatchEvent().

Rules shared by the four cancelable events beforefocus, beforeinput, beforeblur, and linkclick:

  • Listeners run on the spot. After firing the event, the system waits for all listeners to finish before deciding whether to proceed. In a listener, only make the decision; do not do slow work.
  • If any one listener calls preventDefault(), the system does not proceed.
  • A listener throwing is not the same as calling preventDefault().
  • With no listeners, the system handles it the default way.

Content changed by code vs. by the user ​

How it changedFires input?
The user types, deletes, or pastesYes (not verified in the simulator)
insertText(), deleteBackward()Yes (measured)
Writing textNo (measured)

So after writing text in code, update any UI that depends on the content (character count, placeholder text) yourself. Conversely, writing text in an input callback doesn't trigger the callback again.

Size ​

By default the app sets the size of a text view: constraints or frame determine its width and height, and content taller than that scrolls inside it.

Once isScrollEnabled is set to false, it no longer scrolls and instead has a height of its own: it asks to be as tall as its lines of text. When it is positioned with constraints, give only the leading, trailing, and top edges and no height; its height follows the text (measured). This holds only after it is placed in a window: for a text view not in a window, laying it out again after the text changes leaves the height unchanged (measured).

Measured with 17 pt text: one line is 36 pt, three lines 77 pt, five lines 118 pt, six lines 138 pt. With no font set, one line is 30 pt.

Examples ​

Text view with a character count ​

Starting from a blank app, place a text view at the top of the screen with a line of text below it showing the length of the content.

js
application.addEventListener('sceneconnect', (e) => {
  const win = new UIWindow(e.scene);
  const page = new UIViewController();
  page.view.backgroundColor = 'systemBackground';
  win.rootViewController = page;
  win.makeKeyAndVisible();

  const input = new UITextView();
  input.font = UIFont.systemFontOfSize(17);
  input.backgroundColor = 'secondarySystemBackground';
  input.layer.cornerRadius = 10;
  input.keyboardDismissMode = 'onDrag';

  const counter = new UILabel();
  counter.text = 'Length 0';
  counter.textColor = 'secondaryLabel';

  input.addEventListener('input', () => {
    counter.text = 'Length ' + input.text.length;
  });
  input.addEventListener('blur', () => {
    console.log('You typed: ' + input.text);
  });

  input.translatesAutoresizingMaskIntoConstraints = false;
  counter.translatesAutoresizingMaskIntoConstraints = false;
  page.view.addSubview(input);
  page.view.addSubview(counter);
  const safe = page.view.safeAreaLayoutGuide;
  NSLayoutConstraint.activateConstraints([
    input.topAnchor.constraintEqualToAnchor(safe.topAnchor, { constant: 24 }),
    input.leadingAnchor.constraintEqualToAnchor(safe.leadingAnchor, { constant: 16 }),
    input.trailingAnchor.constraintEqualToAnchor(safe.trailingAnchor, { constant: -16 }),
    input.heightAnchor.constraintEqualToConstant(160),
    counter.topAnchor.constraintEqualToAnchor(input.bottomAnchor, { constant: 8 }),
    counter.leadingAnchor.constraintEqualToAnchor(input.leadingAnchor),
  ]);
});

Effect

  • A gray rounded area appears at the top of the screen, with a line of gray text "Length 0" below it.
  • Tapping the gray area brings up the keyboard and a cursor appears in the area.
  • With each character typed, the number in the line below changes. Pressing Return moves to the next line.
  • Once the text is taller than 160 pt, the area can be scrolled vertically.
  • Dragging the text downward dismisses the keyboard, and the console logs You typed: followed by the full content.

This code hasn't been run as a whole in the simulator; the five points above are not verified in the simulator. Reading and writing each property, and the firing of input and blur, were measured in a small program without UI.

Note: When the simulator is connected to the computer's hardware keyboard, the on-screen software keyboard doesn't appear. This is simulator behavior. To see the software keyboard, turn off the hardware keyboard connection in the simulator's menu.

Corresponding iOS API ​

ObjCJS
[[UITextView alloc] init]new UITextView()
view.textinput.text
view.hasTextinput.hasText
[view insertText:@"你好"]input.insertText('你好')
[view deleteBackward]input.deleteBackward()
view.font = [UIFont systemFontOfSize:17]input.font = UIFont.systemFontOfSize(17)
view.textColor = UIColor.labelColorinput.textColor = 'label'
view.textAlignment = NSTextAlignmentCenterinput.textAlignment = 'center'
view.textContainerInset = UIEdgeInsetsMake(12, 12, 12, 12)input.textContainerInset = new UIEdgeInsets(12, 12, 12, 12)
view.textContainer.lineFragmentPadding = 0input.textContainer.lineFragmentPadding = 0
view.textContainer.maximumNumberOfLines = 3input.textContainer.maximumNumberOfLines = 3
view.editable = NOinput.isEditable = false
view.selectable = NOinput.isSelectable = false
view.selectedRange = NSMakeRange(0, 5)input.selectedRange = new NSRange(0, 5)
[view scrollRangeToVisible:range]input.scrollRangeToVisible(range)
view.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDraginput.keyboardDismissMode = 'onDrag'
view.inputAccessoryView = toolbarinput.inputAccessoryView = toolbar
Calling [view reloadInputViews] after changing inputAccessoryViewNot needed. Writing inputAccessoryView takes effect immediately
view.scrollEnabled = NOinput.isScrollEnabled = false

Enum values: drop the type prefix and lowercase the first letter. See Enums.

How UITextViewDelegate methods and notifications map to JS:

ObjCJS
textViewDidBeginEditing:, UITextViewTextDidBeginEditingNotificationfocus event
textViewDidChange:, UITextViewTextDidChangeNotificationinput event
textViewDidEndEditing:, UITextViewTextDidEndEditingNotificationblur event
textViewDidChangeSelection:selectionchange event
textView:shouldChangeTextInRange:replacementText:beforeinput event
textViewShouldBeginEditing:beforefocus event
textViewShouldEndEditing:beforeblur event
textView:primaryActionForTextItem:defaultAction:, when a link was tappedlinkclick event

Compared with the browser <textarea> ​

This table is only for looking up correspondences, for people familiar with HTML forms.

BrowserNacreDifference
textarea.valueinput.text—
input eventinput eventThe event object doesn't carry the content; read input.text
focus / blur eventsfocus / blur events—
selectionStart, selectionEndselectedRangeA start plus a length, not a start plus an end
setRangeText()insertText()Can only replace the current selection
readonlyisEditable = false—
placeholderNoneOverlay a label
maxlengthNoneBlock over-long changes in beforeinput
rowsNoneHeight comes from constraints, or turn off scrolling so it follows the content
selectionchange eventselectionchange eventFires on the text view, not on document. The event object doesn't carry the selection; read input.selectedRange

See also ​