TextEditor in SwiftUI

Gabriel Theodoropoulos
5 min readApr 1, 2021
Photo by Evy Prentice on Unsplash

SwiftUI is great, but it has been lacking of specific native controls, even though that gets much better year by year. One of them was the text view. When SwiftUI was first released, it had no native equivalent of the text view; implementing a custom UIViewRepresentable type to contain UITextView was the only way to go. But since iOS 14, SwiftUI introduces TextEditor, a brand new view to write multi-line text.

Using TextEditor is almost as simple as any other SwiftUI view, with most of common view modifiers to apply here too. The fastest way to use it is to start typing TextEditor and follow Xcode’s auto-suggestion.

TextEditor(text: .constant("Placeholder"))

The argument must be a String binding value, usually a state property, or any other source of truth that gives us a binding value:

@State private var text = ""

Note that using the Binding property wrapper’s constant() method with a default text makes the text editor practically unusable. Editing text is impossible, just because the binding value is a constant and cannot be changed. Also, don't let the "Placeholder" value added automatically by Xcode trick you. It's just a piece of text, and not a real placeholder that will be replaced by actual text while writing, as it happens with the TextView.

TextEditor basics

So, the most common way to get started with TextEditor should be similar to the following:

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

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

While typing, any new additions or changes to the text will be stored to the text state property through the two-way binding value. However, doing just that as the bare minimum implementation has a strange side effect; text is appearing out of the safe area boundary:

This happens automatically, but the way to work around it is simple; adding some padding will place text in the proper position:

TextEditor(text: $text)
.padding()

--

--

Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev