TextEditor is a view in SwiftUI which allows you to display and edit text in your app. The text can consist of multiple lines and can be scrollable. Follow this tutorial to learn how to create, use and style TextEditor in SwiftUI.
In order to initialize a TextEditor, you need to pass in a binding to a @State variable which will store the text entered in the TextEditor:
struct ContentView: View {
@State var text: String = "Simple Swift Guide tutorials."
var body: some View {
TextEditor(text: $text).padding()
}
}
The result should look like the image below. Try tapping on the text to bring up keyboard and type in some text to the editor view.
Styling TextEditor’s Font and Text Color
Standard view modifiers can be used to style TextEditor’s text. In order to change the default font style in the view use the font() modifier and to change the color of the font use foregroundColor() modifier.
Here are the two cases combined into one example setting the font style to headline and text color to red:
TextEditor(text: $text)
.font(.headline)
.foregroundColor(Color.red)
The result should look like this:
You can pass desired font size using the following modifiers:
.font(.system(size: 56.0))
Styling TextEditor’s Text
You can further customize the TextEditor to change the spacing between lines of text, set a line limit or text alignment.
Here is an example setting the alignment to center and spacing between lines to 10 points. In order to better illustrate the case, I modified the text variable to store three lines of text using the new line character:
@State var text: String = "Simple Swift Guide tutorials.\nSimple Swift Guide tutorials.\nSimple Swift Guide tutorials."
TextEditor(text: $text)
.multilineTextAlignment(.center)
.lineSpacing(10.0)
The result should look like this:
Fire an action when input text of TextEditor is modified
In order to run custom code when user modifies the value of text in TextEditor, add the onChange() modifier to the TextEditor:
TextEditor(text: $text)
.onChange(of: text, perform: { value in
print("Value of text modified to = \(text)")
})
The above example will print new value of text every time it gets modified.
How to set TextEditor’s custom size
The size of TextEditor can be set using the frame() modifier:
TextEditor(text: $text)
.frame(minWidth: 0, maxWidth: 150, minHeight: 0, maxHeight: 50)
.border(Color.blue)
We added a border to the TextEditor in the above example in order to illustrate the effect of frame modifier. The result should like like the image below. Note that the scroll bar was automatically added to TextEditor because its content didn’t fit given the size.
Related tutorials:
- SwiftUI TextField complete tutorial
- SwiftUI Text View complete tutorial
- How to add text overlay on image in SwiftUI
Take a look at Apple’s official documentation of TextEditor.