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

--

--

Gabriel Theodoropoulos

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