Skip to content

Instantly share code, notes, and snippets.

@aaronlab
Created January 27, 2021 03:15
Show Gist options
  • Save aaronlab/5cce6d96552a830f3ba6ee6d64df80b0 to your computer and use it in GitHub Desktop.
Save aaronlab/5cce6d96552a830f3ba6ee6d64df80b0 to your computer and use it in GitHub Desktop.
SwiftUI TextEditor Placeholder with NotificationCenter
struct ContentView: View {
@State var text = "Placeholder"
var body: some View {
TextEditor(text: self.$text)
.foregroundColor(self.text == "Placeholder" ? .gray : .primary)
.onAppear {
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { (noti) in
withAnimation {
if self.text == "Placeholder" {
self.text = ""
}
}
}
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { (noti) in
withAnimation {
if self.text == "" {
self.text = "Placeholder"
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment