[英]SwiftUI TextField to reset focus on any click
I want to do this: Click on any element except the current "Textfield" and the keyboard - the logic of losing focus is called.我想这样做:单击除当前“文本字段”和键盘之外的任何元素 - 调用失去焦点的逻辑。
struct ContentView: View {
@State private var text: String = ""
var body: some View {
VStack {
Text("Hello, world!")
TextField(
"Title TextField",
text: self.$text,
onEditingChanged: {
print("onEditingChanged: \($0)")
},
onCommit: {
print("onCommit")
}
)
.onSubmit {
print("onSubmit")
}
Button("Print") {
print("text: \(self.text)")
}
}
}
}
I would like to make a universal solution without the need to manually hide the keyboard.我想制作一个通用的解决方案,而无需手动隐藏键盘。
I need this because TextField has different logic in iOS 14 and iOS 15.我需要这个是因为 TextField 在 iOS 14 和 iOS 15 中有不同的逻辑。
iOS 14: value changes after the keyboard is closed. iOS 14:键盘关闭后值会发生变化。
iOS 15: value changes when entering from the keyboard. iOS 15:从键盘输入时值会发生变化。
I use this extension:我使用这个扩展:
extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
And then in my body:然后在我的身体里:
.onTapGesture {
UIApplication.shared.endEditing()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.