How to add placeholder text to TextEditor in SwiftUI?

后端 未结 9 2162
逝去的感伤
逝去的感伤 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:44

    With an overlay, you won't be able to allow touch on the placeholder text for the user to write in the textEditor. You better work on the background, which is a view.

    So, create it, while deactivating the default background:

    struct PlaceholderBg: View {
    
    let text: String?
    
    init(text:String? = nil) {
            UITextView.appearance().backgroundColor = .clear // necessary to remove the default bg
        
        self.text = text
     }
    
    var body: some View {
        VStack {
        HStack{
        
        Text(text!)
              
        Spacer()
        }
        Spacer()
        }
    }
        
    }
    

    then, in your textEditor:

     TextEditor(text: $yourVariable)
                            
                            .frame(width: x, y)
                            .background(yourVariable.isEmpty ? PlaceholderBg(texte: "my placeholder text") : PlaceholderBG(texte:""))
    

提交回复
热议问题