Aim
- To use a keyboard shortcut on a Multiplatform app (iOS and macOS)
- When keyboard shortcut is tapped, the price needs to be printed
Problem
- The same code doesn't work on iPad but works on macOS
Question:
- Why is not working?
- How to fix this?
Environment
- macOS Big Sur - 11.6 (20G165)
- Version 13.0 (13A233)
Code
@main
struct TestApp: App {
@State private var price = 0
var body: some Scene {
WindowGroup {
ContentView(price: $price)
.focusedValue(\.price, $price)
}
.commands {
PriceCommands()
}
}
}
struct ContentView: View {
@Binding var price: Int
var body: some View {
IncreasePriceButton(price: $price)
}
}
struct IncreasePriceButton: View {
@Binding var price: Int
var body: some View {
Button("Increase Price") {
price += 1
print("price = \(price)")
}
}
}
struct PriceCommandButton: View {
@FocusedBinding(\.price) var price
var body: some View {
Button("Print Price") {
print("price = \(price)")
}
}
}
struct PriceCommands: Commands {
var body: some Commands {
CommandMenu("Custom") {
PriceCommandButton()
.keyboardShortcut(KeyboardShortcut("C", modifiers: [.command, .shift]))
}
}
}
struct FocusedPriceKey: FocusedValueKey {
typealias Value = Binding<Int>
}
extension FocusedValues {
var price: FocusedPriceKey.Value? {
get { self[FocusedPriceKey.self] }
set { self[FocusedPriceKey.self] = newValue }
}
}