How to add placeholder text to TextEditor in SwiftUI?

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

    As I know, this is the best way to add a placeholder text to TextEditor in SwiftUI

    struct ContentView: View {
        @State var text = "Type here"
        
        var body: some View {
    
            TextEditor(text: self.$text)
                // make the color of the placeholder gray
                .foregroundColor(self.text == "Type here" ? .gray : .primary)
                
                .onAppear {
    
                    // remove the placeholder text when keyboard appears
                    NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { (noti) in
                        withAnimation {
                            if self.text == "Type here" {
                                self.text = ""
                            }
                        }
                    }
                    
                    // put back the placeholder text if the user dismisses the keyboard without adding any text
                    NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { (noti) in
                        withAnimation {
                            if self.text == "" {
                                self.text = "Type here"
                            }
                        }
                    }
                }
        }
    }
    

提交回复
热议问题