Chapter 32
Working with TextEditor and Multiline Text Fields

The first version of SwiftUI, released along with iOS 13, didn't come with a native UI component for a multiline text field. To support multiline input, developers had to wrap a UITextView from the UIKit framework and make it available to their SwiftUI project by adopting the UIViewRepresentable protocol. In iOS 14, Apple introduced a new component called TextEditor for the SwiftUI framework. This TextEditor enables developers to display and edit multiline text in your apps. Additionally, in iOS 16, Apple further improved the built-in TextField to support multiline input.

In this chapter, we will demonstrate how to utilize both TextEditor and TextField for handling multiline input in your SwiftUI apps.

Using TextEditor

It is very easy to use TextEditor. You simply need to have a state variable to hold the input text. Then, create a TextEditor instance in the body of your view, like this:

struct ContentView: View {
    @State private var inputText = ""

    var body: some View {
        TextEditor(text: $inputText)
    }
}

To instantiate the text editor, you pass the binding of inputText so that the state variable can store the user input.

You can customize the editor like any other SwiftUI view. For example, the code below changes the font type and adjusts the line spacing of the text editor:

TextEditor(text: $inputText)
    .font(.title)
    .lineSpacing(20)
    .autocapitalization(.words)
    .disableAutocorrection(true)
    .padding()

Optionally, you can enable/disable the auto-capitalization and auto-correction features.

Figure 1. Using TextEditor
Figure 1. Using TextEditor

Using the onChange() Modifier to Detect Text Input Change

In UIKit, UITextView works with the UITextViewDelegate protocol to handle editing changes. So, how about TextEditor in SwiftUI? How do we detect the change of user input and perform further processing?

The SwiftUI framework provides an onChange() modifier, which can be attached to TextEditor or any other views to detect state changes. Let's say you are building a note application using TextEditor and need to display a word count in real time. You can attach the onChange() modifier to TextEditor like this:

To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.

results matching ""

    No results matching ""