Here's my SwiftUI
code:
struct ContentView : View {
@State var showingTextField = false
@State var text = ""
var body: some View {
return VStack {
if showingTextField {
TextField($text)
}
Button(action: { self.showingTextField.toggle() }) {
Text ("Show")
}
}
}
}
What I want is when the text field becomes visible, to make the text field become the first responder (i.e. receive focus & have the keyboard pop up).
Best Answer
Swift UI 3
As of Xcode 13, you can use the
focused
modifier to make a view become first responder.Swift UI 1/2
It doesn't seem to be possible at the moment, but you can implement something similar yourself.
You can create a custom text field and add a value to make it become first responder.
Note:
didBecomeFirstResponder
is needed to make sure the text field becomes first responder only once, not on every refresh bySwiftUI
!You would use it like this...
P.S. I added a
frame
as it doesn't behave like the stockTextField
, meaning there's more stuff going on behind the scenes.More on
Coordinators
in this excellent WWDC 19 talk: Integrating SwiftUITested on Xcode 11.4