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

问题描述

当您按下 intro 并使用 keyboardSwiftUI关闭 TextField 时,您是否尝试过处理该事件?

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

我如何知道用户 dismiss keyboard 何时按下了“介绍”按钮?

非常感谢!

enter image description here

解决方法

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

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 = {})
,

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

整体看起来是这样

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

此视频在 8:00 左右进行了解释。

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