Friday, July 30, 2021

Implementing a Focusable Text Field in SwiftUI

Gabriel Theodoropoulos (via Dave Verwer):

What I mentioned above is definitely good news, but it regards evolvements that are going to be working in macOS Monterey and above. That’s nice, but what about backward compatibility? What if we wanted to make apps that support macOS versions prior to Monterey, such as Big Sur or Catalina?

The answer to these questions is what this post is all about. In the following parts, I will take you step by step through the implementation of a custom text field capable of:

  1. Getting the focus automatically when a view appears; that means that the text field will be ready to start typing into without clicking on it first.
  2. Moving the focus on subsequent text fields by pressing the Tab key.

I still find it surprising—or maybe not, since it was designed for a device with neither a mouse nor a keyboard—that it took three releases for SwiftUI to get the equivalent of firstResponder, one of the most basic Cocoa concepts. Maybe in a few more years it will support setting the nextKeyView.

Jonathan Wight:

< 400 lines of SwiftUI

That said I can’t figure out how to layout a resizable username/password login dialog without hardcoding widths or breaking causality.

Rob Napier:

The paradox of SwiftUI.

I find it utterly infuriating and incredibly promising.

Previously:

Comments RSS · Twitter

Leave a Comment