Black Friday deal: 30% off our book "Integrating SwiftUI into UIKit apps"! Learn more ...Black Friday deal:30% off "Integrating SwiftUI into UIKit apps" >>

Use KeyPath to drive programmatic focus

Starting from iOS 15 and macOS 12 we have focused(_:equals:) modifier that allows us to programmatically control focus in our app and respond to focus changes. It works together with FocusState property wrapper.

Common examples of focused(_:equals:) and FocusState define their custom enum for FocusState and use it to enable switching between the fields in a form. But in most cases the fields of a form naturally associate themselves with fields in your model.

Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover
Black Friday offer
Our book "Integrating SwiftUI into UIKit apps" is now 30% off!

Discover various ways to adopt SwiftUI in existing UIKit projects and take full advantage of the new iOS 16 frameworks and APIs such as Swift Charts.

The offer is active until the 1st of December.

I find it more convenient to use KeyPath as the focus state value. And since the value only needs to conform to Hashable we can even use AnyKeyPath as the type, so that we can handle focus across multiple fields spanning more than one model.

struct ContentView: View {
    @State var project = Project()
    
    @FocusState var focus: AnyKeyPath?
    
    var body: some View {
        Form {
            TextField("Name", text: $project.name)
                .focused($focus, equals: \Project.name)
            
            TextEditor(text: $project.body)
                .focused($focus, equals: \Project.body)
        }
    }
}

Adding a submit button to the form lets us validate it and, if needed, focus the user on the field that is missing a value.

Button("Submit") {
    guard project.name != "" else {
        focus = \Project.name
        return
    }
    guard project.body != "" else {
        focus = \Project.body
        return
    }
    ... // Do something here
}

In addition, we can add onAppear(perform:) modifier to the form, so that we can drive focus as soon as the form appears on screen.

.onAppear {
    guard project.name != "" else {
        focus = \Project.name
        return
    }
    guard project.body != "" else {
        focus = \Project.body
        return
    }
}

Responding to focus changes can sometimes also be useful. In the following example we can force the focus back to the name field by adding onChange(of:perform:) modifier to the form.

.onChange(of: focus) { newValue in
    if project.name == "" {
        focus = \Project.name
    }
}