How can I remove Textfield focus when I press return or click outside Textfield? Note that this is SwiftUI on MacOS.
If I do this:
import SwiftUI
struct ContentView: View {
@State var field1: String = "This is the Text Field View"
var body: some View {
VStack{
Button("Press") {
print("Button Pressed")
}
TextField("Fill in Text", text: Binding(
get: { print("get") ; return self.field1 },
set: { print("set") ; self.field1 = $0 }
)
)
}
}
}
then click into the TextField and edit it then click on the Button the TextField does not lose focus. How can I make it exit editing mode and lose focus.
I would also like to lose focus from the TextField if I press Return. I used the Binding initialiser with get and set because I thought I could somehow intercept keypresses and detect the 'Return' character but this doesn't work.
Any help appreciated :-)
If you're supporting only iOS 15 and later, you can activate and dismiss the keyboard for a text field by focusing and unfocusing it. In its simplest form, this is done using the @FocusState property wrapper and the focusable() modifier – the first stores a Boolean that tracks whether the second is currently focused.
Moving SwiftUI View Up When Keyboard AppearsCreate keyboard height state. SwiftUI will automatically update the view whenever the keyboard height changes. Add padding to the bottom of the view, which will make it move up and down with the keyboard.
A TextField is a type of control that shows an editable text interface. In SwiftUI, a TextField typically requires a placeholder text which acts similar to a hint, and a State variable that will accept the input from the user (which is usually a Text value).
Here are possible variants
import SwiftUI
import AppKit
struct ContentView: View {
@State var field1: String = "This is the Text Field View"
var body: some View {
VStack{
Button("Press") {
print("Button Pressed")
NSApp.keyWindow?.makeFirstResponder(nil)
}
TextField("Fill in Text", text: Binding(
get: { print("get") ; return self.field1 },
set: { print("set") ; self.field1 = $0 }
), onCommit: {
DispatchQueue.main.async {
NSApp.keyWindow?.makeFirstResponder(nil)
}
}
)
}
}
}
backup
Just add a onTapGesture
to your VStack
with the following line:
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, for:nil)
This code will close the keyboard.
Example:
VStack {
// ...
}.onTapGesture {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, for:nil)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With