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.
iOS 14: value changes after the keyboard is closed.
iOS 15: value changes when entering from the keyboard.
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()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.