当 TextEditor 失去焦点时如何得到通知?

How to be notified when a TextEditor loses focus?

在我的 SwiftUI 应用程序中,我希望在 TextEditor 丢失 focus/has 完成编辑时收到通知。理想情况下,TextFieldonCommit 回调是完美的。

使用下面的新 onChange 确实可以接收用户键入的每个新字符,但我真的很想知道它们何时完成。

@State var notes = ""
...

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

我想通了,你可以使用 UIResponder.keyboardWillHideNotification.

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

在 iOS 15.0 上,现在有 @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
        }
    }
  }
}