I would like to implement a focus-based Menu-Bar command in my SwiftUI iPadOS app, or react to key command while certain elements are focused.
Traditionally, this requires using @FocusedValue and focusable() and focused, however, it appears that setting a @FocusState on macOS will work, but setting a @FocusState on iPadOS will never work.
How can this API work and support MenuBar commands and keyboard inputs? It kind of has an accessibility impact as well. Not all users are going to know, or want to turn on "full keyboard control" for basic interactions.
Here's a small sample that doesn't appear to focus on iPadOS:
struct FocusableTestView: View {
@FocusState private var isRectFocused: Bool
var body: some View {
VStack {
// This text field should focus the custom input when pressing return:
TextField("Enter text", text: .constant(""))
.textFieldStyle(.roundedBorder)
.onSubmit {
isRectFocused = true
}
.onKeyPress(.return) {
isRectFocused = true
return .handled
}
// This custom "input" should focus itself when tapped:
Rectangle()
.fill(isRectFocused ? Color.accentColor : Color.gray.opacity(0.3))
.frame(width: 100, height: 100)
.overlay(
Text(isRectFocused ? "Focused" : "Tap me")
)
.focusable(true)
.focused($isRectFocused)
.onTapGesture {
isRectFocused = true
print("Focused rectangle")
}
// The focus should be able to be controlled externally:
Button("Toggle Focus") {
isRectFocused.toggle()
}
.buttonStyle(.bordered)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
}
}