SwiftUI: Autofocusing a TextField

SwiftUI continues to amaze and infuriate me. I’m astonished at how quickly I can get a user interface built, but it’s the minor details that cause immense frustration during the final 10% of development.

Autofocusing a TextField is just one of many issues I’ve stumbled upon this week.

At the time of writing, SwiftUI can’t do this on its own, you’ll need to drop to UIKit and make a subclass of a UITextField to set .didBecomeFirstResponder to “true”.

I won’t go over how to do this here. This Stack Overflow article has the details on how to do it.

If like me, you need to have your autofocusing text field in a sheet, you’ll potentially run into an issue - depnding on what you’re running it on, your app could crash. As Robert Ying helpfully points out, this is because (in some cases) you cannot call .didBecomeFirstResponder on your textfield that’s in a sheet before the textfield has been shown.

To get around the issue, you can add a check to see if the textfield’s window is nil before calling .didBecomeFirstResponder, therefore avoiding the crash if the textfield isn’t ready.

For me, this semi-solves the issue. It works great on the Mac (using SwiftUI via Catalyst), but not on the iPhone and iPad, the app doesn’t crash on iOS (thanks to the nil check), it just doesn’t autofocus onto the textfield.

Removing the nil check will make things work correctly on the iPhone, and it still works correctly on the Mac (as it already did with the nil check), but it crashes on iPad – in the simulator as least. Currently, I’m not in a position to do any on device testing.

Could this be something that gets fixed in an update via Apple?

This is my dilemma with SwiftUI at the moment. Odd things like this crop up, and you’re never quite sure if it’s you at fault, or if it’s something that Apple will fix in due course. Do I sink hours into investigations, or put this to one side and hope that Apple will magically fix my issue?

Looking at when Robert posted his answer on Stack Overflow, it was August 2019 during the beta season. Given that the iPhone and Mac don’t crash at the time of writing (Feb 1st 2020), it would suggest that perhaps Apple have made some improvements since August 2019, and just the iPad remains to be fixed. Hard to say for sure, I guess this is the price we pay for living on the bleeding edge.

If you have any extra information regarding this, I’m all ears. Feel free to come and yell at me on Twitter.

Dave Nott @_davenott