How to add placeholder text to TextEditor in SwiftUI?

后端 未结 9 2313
逝去的感伤
逝去的感伤 2021-02-14 01:35

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?<

9条回答
  •  没有蜡笔的小新
    2021-02-14 01:50

    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()
      }
    }
    

提交回复
热议问题