Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Text Editor in SwiftUI
Written by Team Kodeco

In SwiftUI, TextEditor is a multiline text entry control that can be used when you want the user to input more than a single line of text, such as in a note-taking app or a chat app where users can enter a multi-line message. The TextEditor control behaves much like a UITextView in UIKit, Apple’s older user interface framework.

To create a TextEditor in SwiftUI, you would typically create a state variable to store the user’s input, and then bind that state to the TextEditor. Here’s an example:

struct ContentView: View {
  @State private var enteredText = "Type something..."

  var body: some View {
    TextEditor(text: $enteredText)
      .padding()
      .font(.title)
      .foregroundColor(.gray)
  }
}

Here’s what your preview should look like:

A text editor in SwiftUI.
A text editor in SwiftUI.

In this code:

  • @State private var enteredText = "Type something..." creates a state variable, enteredText, that’s used to store the text entered by the user.

  • TextEditor(text: $enteredText) creates the TextEditor itself. It takes a binding to the enteredText property.

  • .padding() adds padding around the text editor.

  • .font(.title) and .foregroundColor(.gray) modify the font and color of the text, respectively.

As the user types, the entered text is updated in real time. Because it’s a @State property, any changes to enteredText will cause the view to be re-rendered, so your UI will always be up to date with the latest text.

The TextEditor control in SwiftUI offers a flexible, easy-to-use interface for accepting multiline text input from users. With this understanding, you can now build interfaces in your app that can accept and handle multiline text inputs.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.