Search code examples
iosswiftswiftuiios14

How to be notified when a TextEditor loses focus?


In my SwiftUI app, I would like to be notified when the TextEditor loses focus/has finished editing. Ideally, something like TextField's onCommit callback would be perfect.

Using the new onChange as below does work for receiving every new character that the user types, but I really want to know when they are finished.

@State var notes = ""
...

TextEditor(text: $notes)
    .onChange(of: notes, perform: { newString in
        print(newString)
    })

Solution

  • I figured it out, you can use the UIResponder.keyboardWillHideNotification.

    TextEditor(text: $notes)
        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
            print("done editing!")
        }