Date:

Share:

Keyboard driven navigation with focusable() on iPad in SwiftUI

Related Articles

The latest updates to iOS 17 and iPadOS 17 brought exciting changes, one of which is the introduction of the can focus() device. This allows us to allow users to focus on views that are not focusable by default, which significantly improves keyboard-based interaction.

Here is a simple example of how we can use focusable() Changer in SwiftUI.

VStack {
    FirstView()
        .focusable()

    SecondView()
        .focusable()
}
Integrating SwiftUI in UIKit apps by Natalia Panprovova book coverIntegrating SwiftUI in UIKit apps by Natalia Panprovova book cover
WWDC23 proposal

our book “Integrating SwiftUI in UIKit apps” now 40% discount!

Discover different 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 sale is active until 19.6.

#

Customize the focus effect style

To customize the focus effect style we need to remove the default style with focusEffectDisabled() Then apply ours.

To know that a view is focused we need to use concentrated() Mishna with a @FocusState Track changes and react to them.

struct ContentView: View {
    var body: some View {
        VStack {
            FirstViewWrapped()
                .focusEffectDisabled()

            SecondView()
                .focusable()
        }
    }
}

struct FirstViewWrapped: View {
    @FocusState var isFocused
        
    var body: some View {
        FirstView()

            .focusable()             // Enable focuses
            .focused($isFocused)     // Detect focuses
            
            .background {
                if isFocused {
                    Capsule()
                        .fill(.indigo)
                        .opacity(0.3)
                }
            }
    }
}

The order of the focusable() and focused() This sub is important. God focused() The change must be placed after the focusable() device.

A screenshot showing a focused SwiftUI view with a custom background style.

If you enjoy our blog and would like to support us, you can Sponsor us on GitHub.

For blog updates and development tips, follow us on Twitter @nilcoalescing.

Source

Popular Articles