I'm making an iOS application which can use hardware keyboard or run on Apple-Silicon macs. It seems that macos apps can take use of a very convenient APIs for checking if some of the modifier keys are pressed (How to check if Option key is down when user clicks a NSButton) like BOOL alt = [NSEvent modifierFlags] & NSAlternateKeyMask
. This is exactly what I want, but I can't find anything like this for iOS-based app.
UIEvent has modifierFlags but only as an instance property.
NSEvent has both instance modifierFlags as well as static modifierFlags which can be used for querying the state anywhere inside the app without bothering with observing keyboard events.
You can write such a static property yourself, and update it as the key presses change, by overriding pressesBegan
/pressesEnded
in your app delegate/scene delegate (or anywhere else along the responder chain).
extension UIEvent {
fileprivate(set) static var modifierKeys: UIKeyModifierFlags = []
}
// ...
override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
UIEvent.modifierKeys.formUnion(event?.modifierFlags ?? [])
}
override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
UIEvent.modifierKeys.formIntersection(event?.modifierFlags ?? [])
}
override func pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
UIEvent.modifierKeys.formIntersection(event?.modifierFlags ?? [])
}