How to add multi-line text input option in SwiftUI?
We use SwiftUI’s TextField when the user wishes to input short text strings. However, you should switch to a TextEditor view for longer pieces of text.
Just like TextField, it requires a two-way binding to a text string, but it has the added bonus of allowing several lines of text — it’s much more suitable for taking larger strings from the user.
TextEditor is simpler to use than TextField, however, it has no special configuration options; you cannot modify its style or add placeholder text; instead, you just bind it to a string.
However, care must be taken to ensure that it does not extend beyond the safe region; if it does, typing will be difficult; embed it in a NavigationView, a Form, or something similar.
Code for multi-line text input option in SwiftUI?
The code for accepting multi-line text input with TextEditor
struct ContentView: View {
@State private var notes = ""
var body: some View {
NavigationView {
TextEditor(text: $notes)
.navigationTitle("Notes")
.padding()
}
}
}
How to add a border to multi-line TextEditor ?
You can use the .border modifier to add a border to your multi-line text editor
.border(Color.red, width: 5)
How to add a frame with a border to multi-line TextEditor?
Alternatively, you can use the following modifiers to TextEditor to add frame and border to your editor
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 200)
.border(Color.red, width: 2)
How to add a background color to TextEditor?
There is no straight way or modifier by which we can add a background color to the Text Editor. But there is a work through, a little hack, we will wrap it in a ZStack with a Background Color and then remove the background color of the UITextView on appear. The complete code is :-
struct ContentView: View {
@State private var notes = ""
var body: some View {
NavigationView {
ZStack{
Color.red
TextEditor(text: $notes)
.foregroundColor(Color.blue)
.navigationTitle("Notes")
.padding()
.border(Color.blue, width: 5)
}.onAppear() {
UITextView.appearance().backgroundColor = .clear
}
}
}
}