SwiftUI Keyboard Shortcut Scop... Note

SwiftUI Keyboard Shortcut Scope

SwiftUI's .keyboardShortcut modifier, introduced in iOS 14, allows assigning keyboard shortcuts to controls. These shortcuts trigger the control's primary action. The modifier can customize modifier keys beyond the default command key. A key example shows navigation between views with shortcuts applied to buttons. Surprisingly, shortcuts remain active even when the associated control is offscreen. This behavior stems from SwiftUI's depth-first traversal of the view hierarchy to find shortcut targets. The system prioritizes finding the first matching control, regardless of visibility. This can lead to unexpected behavior where offscreen controls still respond to shortcuts. A workaround involves disabling controls using the .disabled modifier based on view state. This ensures shortcuts are only active when the relevant controls are visible. Curt Clifton's comment provides additional context.
CdXz5zHNQW_hbjMzJI3Vw.png