Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    })
like image 396
Jeremy Avatar asked Oct 22 '25 16:10

Jeremy


1 Answers

On iOS 15.0, there is now @FocusState.

struct MyView: View {

  @State var text: String
  @FocusState private var isFocused: Bool

  var body: some View {
    Form {
      TextEditor(text: $text)
        .focused($isFocused)
        .onChange(of: isFocused) { isFocused in
          // do stuff based off focus state change
        }
    }
  }
}
like image 87
kgaidis Avatar answered Oct 25 '25 06:10

kgaidis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!