124 - Create a Text Editor in SwiftUI

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.

In this code:

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.