Focus Management in SwiftUI: Getting Started

Focus Management in SwiftUI: Getting Started

Remember the last time you logged in, completed a checkout process, or sent feedback? Each of these interactions likely included a form. Navigating a form can be tedious if the app doesn’t assist with focus. When a view is focused, it’s visually activated and ready for interaction. A view type you might associate with focus is a text field: Often, focus is applied to text fields to bring up the keyboard and tip off the user to type in that field next.

To simplify focus implementation, Apple introduced FocusState at WWDC 2021. FocusState is a property wrapper that tracks and edits the focus location in the scene.

In this tutorial, you’ll learn all about focus management in SwiftUI by using modifiers and wrappers like FocusState to help users navigate forms more effectively. You’ll do so by filling out a checkout form and gift card for a friend. How nice of you! :]

[…]

Download the starter project by clicking Download Materials at the top or bottom of this tutorial. Open the project in the starter directory in Xcode. Build and run on an iPhone simulator.

The app displays a list of available gifts. Select a gift, then enter shipping information. Finally, write a gift message along with the recipient’s email addresses.

You may notice that some focus improvements could be made. For example, focus should shift seamlessly between shipping fields when the user taps the return key. And, when trying to proceed to the next step, focus should draw the user to invalid entries.

In the next section, you’ll learn about FocusState and how it can help the user start filling out your form quickly.

If you’re looking for model-view-viewmodel (MVVM) pattern specifically, checkout Design Patterns by Tutorials: MVVM.

[…]