跳转至
Structure

TextEditor

A multi-line text field.

Declaration

struct TextEditor : View

Overview

A text editor view allows you to display and edit multiline, scrollable text in your app's user interface. The text editor responds to usual view modifiers like:

Creating a text editor

You create a text editor by adding a TextEditor instance to the body of your view, and initialize it by passing in a Binding to a string variable in your app:

struct TextEditingView: View {
    @State private var fullText = "This is some editable text..."

    var body: some View {
        TextEditor(text: $fullText)
            .padding()
    }
}
A screenshot displaying a keyboard on the lower half of the screen with text that reads "This is some editable text..." which can be edited by the user with as many lines as necessary.

Styling a text editor

To style the text, use the standard view modifiers to configure a system font, set a custom font, or change the color of the view's text.

In this example, the view renders the editor's text in gray with a custom font:

struct TextEditingView: View {
    @State private var fullText = "This is some editable text..."

    var body: some View {
        TextEditor(text: $fullText)
            .foregroundColor(Color.gray)
            .font(.custom("HelveticaNeue", size: 13))
            .padding()
    }
}
A screenshot displaying a keyboard on the lower half of the screen with text that reads "This is some editable text..." which has a style applied such that the font is Helvetica Neue with a large 13 pt.

If you want to change the spacing or font scaling aspects of the text, you can use modifiers like lineLimit(_:), lineSpacing(_:), and minimumScaleFactor(_:) to configure how the view displays text depending on the space constraints. For example, here the lineSpacing(_:) modifier sets the spacing between lines to 5 points:

struct TextEditingView: View {
    @State private var fullText = "This is some editable text..."

    var body: some View {
        TextEditor(text: $fullText)
            .lineLimit(3)
            .lineSpacing(5)
            .minimumScaleFactor(0.5)
            .padding()
    }
}
A screenshot displaying a keyboard on the lower half of the screen with text that reads "This is some editable text..." which has a style applied such that the spacing between lines is 5 pt.

Availability

iOS 14.0+

macOS 11.0+

Topics


Instance Property

body The content and behavior of the view.


Initializer

init(text:) Creates a multi-line text field.


Type Alias

Body The type of view representing the body of this view.