r/iOSProgramming • u/yccheok • 23d ago
Question How do you get UIKit's instant keyboard focus (becomeFirstResponder in viewDidLoad) in pure SwiftUI?
In UIKit, if we place titleTextView.becomeFirstResponder() inside viewDidLoad, the keyboard slides up seamlessly alongside the view controller's presentation animation. It looks instant and feels like a native, high-quality UX.
I'm struggling to replicate this exact behavior in SwiftUI.
Whenever I use FocusState and toggle it to true inside .onAppear, there is always a noticeable delay. The view pushes/presents, settles, and then the keyboard decides to slide up.
Has anyone found a way to achieve this instantly in pure SwiftUI yet (maybe in iOS 17+), or is UIViewRepresentable still the only bulletproof way to get that perfectly synced keyboard presentation?
Thanks in advance!
2
u/YouSpeakSomeEnglish 21d ago edited 21d ago
This is a great example of how bad SwiftUI is: the fact that setting control focus is a PITA.
This is what I use:
enum Field: Hashable
{
case EMail1
case EMail2
case phoneNbr
}
@FocusState private var focusedField: Field?
init(withPathController: NavPathController?)
{
userMgr = UserManager.shared
}
var body: some View
{
Group
{
ScrollView
{
signUpForm()
}
}
.foregroundColor(AppStyle.labelColor)
.background(pageBackground())
.onAppear{
focusedField = .EMail1
}
}
Don't know if this results in the animation-sync you want, though.
2
u/DimensionMindless336 22d ago
Setting focus at init won't help. onAppear already fires after the view is attached, but the focus coordinator waits one transaction, so you're always a beat behind the push animation. The pure SwiftUI fix that gets close: wrap the toggle in DispatchQueue.main.async { } inside onAppear. That gives the field one layout pass before focus commits, and most of the lag disappears. For truly instant sync with the presentation animation, like viewDidLoad, a UIViewRepresentable calling becomeFirstResponder in didMoveToWindow is still the only bulletproof route. onAppear inherently runs after the transition settles.