When using SwiftUI\'s new TextEditor, you can modify its content directly using a @State. However, I haven\'t see a way to add a placeholder text to it. Is it doable right now?<
SwiftUI TextEditor
does not yet have support for a placeholder. As a result, we have to "fake" it.
Other solutions had problems like bad alignment or color issues. This is the closest I got to simulating a real placeholder. This solution "overlays" a TextField
over the TextEditor
. The TextField
contains the placeholder. The TextField
gets hidden as soon as a character is inputted into the TextEditor
.
import SwiftUI
struct Testing: View {
@State private var textEditorText = ""
@State private var textFieldText = ""
var body: some View {
VStack {
Text("Testing Placeholder Example")
ZStack(alignment: Alignment(horizontal: .center, vertical: .top)) {
TextEditor(text: $textEditorText)
.padding(EdgeInsets(top: -7, leading: -4, bottom: -7, trailing: -4)) // fix padding not aligning with TextField
if textEditorText.isEmpty {
TextField("Placeholder text here", text: $textFieldText)
.disabled(true) // don't allow for it to be tapped
}
}
}
}
}
struct Testing_Previews: PreviewProvider {
static var previews: some View {
Testing()
}
}