TextField "Intro" 点击键盘 SwiftUI (iOS 14)

TextField "Intro" Tap on the keyboard SwiftUI (iOS 14)

您是否曾尝试在按下 intro 时处理事件,并使用 TextFieldSwiftUI 中关闭 keyboard

TextField("type your name here", text: $yourName)

我怎么知道用户 dismiss keyboard 按下了 'intro' 按钮?

非常感谢!

声明TextField后,添加一个闭包并用以下代码填充它:UIApplication.shared.keyWindow?.endEditing(true)

所以看起来像

TextField($yourText){
    UIApplication.shared.keyWindow?.endEditing(true)
}

此视频中围绕 8:00 标记进行了解释。

https://www.youtube.com/watch?v=TfJ70vHABjs

您可以使用 TextField 中的 onCommit 参数。这是一个例子:

TextField("type your name here", text: $yourName, onCommit: {
    print("return key pressed")
})

来自文档:

/// [...]
///   - onCommit: An action to perform when the user performs an action
///     (for example, when the user presses the Return key) while the text
///     field has focus.
public init(_ titleKey: LocalizedStringKey, text: Binding<String>, onEditingChanged: @escaping (Bool) -> Void = { _ in }, onCommit: @escaping () -> Void = {})