【问题标题】:How to be notified when a TextEditor loses focus?当 TextEditor 失去焦点时如何得到通知?
【发布时间】:2020-08-28 22:33:04
【问题描述】:

在我的 SwiftUI 应用程序中,我希望在 TextEditor 失去焦点/完成编辑时收到通知。理想情况下,像 TextFieldonCommit 回调这样的东西会很完美。

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

@State var notes = ""
...

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

【问题讨论】:

    标签: ios swift swiftui ios14


    【解决方案1】:

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

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

    【讨论】:

    • 如果您有一个表单并且焦点移动到下一个可编辑字段而不隐藏键盘,这将不起作用。
    【解决方案2】:

    在 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
            }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多