Skip to content
DeveloperMemos

How to Use SwiftUI's TextEditor view

SwiftUI, TextEditor, iOS Development1 min read

The TextEditor view in SwiftUI is one of the most useful views when it comes to handling user input. In this article, we'll take a look at how to use the TextEditor view in SwiftUI and show some examples.

Creating a Basic TextEditor

The TextEditor view is very simple to use. To create a basic text editor, you can simply add the following code to your SwiftUI view:

1struct ContentView: View {
2 @State private var text = ""
3
4 var body: some View {
5 TextEditor(text: $text)
6 .frame(height: 200)
7 .border(Color.gray)
8 }
9}

This code creates a TextEditor with an initial empty string value and sets its frame height to 200 points. It also adds a gray border around the TextEditor.

Setting the TextEditor Style

You can customize the appearance of the TextEditor by applying a style. SwiftUI comes with some built-in styles that you can use or you can create your own custom style. Here's an example of how to use a built-in style:

1struct ContentView: View {
2 @State private var text = ""
3
4 var body: some View {
5 TextEditor(text: $text)
6 .font(.headline)
7 .foregroundColor(.blue)
8 .padding()
9 .background(Color.yellow)
10 .cornerRadius(10)
11 .shadow(radius: 5)
12 }
13}

This code sets the font to headline, the text color to blue, and adds padding around the TextEditor. It also sets the background to yellow, adds a corner radius of 10 points, and adds a shadow with a radius of 5 points.

Limiting Text Input

Sometimes you may want to limit the number of characters a user can input into a TextEditor. You can achieve this by using the maxLength parameter. Here's an example:

1struct ContentView: View {
2 @State private var text = ""
3 let maxCharacters = 20
4
5 var body: some View {
6 VStack {
7 Text("Character count: \(text.count)/\(maxCharacters)")
8 .font(.caption)
9 .foregroundColor(text.count <= maxCharacters ? .green : .red)
10 .padding(.bottom)
11
12 TextEditor(text: $text)
13 .frame(height: 200)
14 .border(Color.gray)
15 .cornerRadius(10)
16 .padding()
17
18 }
19 .onChange(of: text) { newValue in
20 if newValue.count > maxCharacters {
21 text = String(newValue.prefix(maxCharacters))
22 }
23 }
24
25 }
26}

This code creates a TextEditor with a maximum character count of 20. It also displays a message below the TextEditor showing how many characters have been entered and whether the user has exceeded the limit. If the user exceeds the limit, the extra characters are automatically removed.

In Closing

The TextEditor view in SwiftUI is a powerful tool for managing user input in your iOS apps. With just a few lines of code, you can create a multi-line text editor with various formatting options. Hopefully, this tutorial has given you some ideas on how to use the TextEditor view in your next SwiftUI project.