I want to have a Bool property, that represents that option key is pressed @Publised var isOptionPressed = false. I would use it for changing SwiftUI View.
For that, I think, that I should use Combine to observe for key pressure.
I tried to find an NSNotification for that event, but it seems to me that there are no any NSNotification, that could be useful to me.
Since you are working through SwiftUI, I would recommend taking things just a step beyond watching a Publisher and put the state of the modifier flags in the SwiftUI
Environment. It is my opinion that it will fit in nicely with SwiftUI's declarative syntax.I had another implementation of this, but took the solution you found and adapted it.
Note that my event closure is returning the event passed in. If you return
nilyou will prevent the event from going farther and someone else in the system may want to see it.The struct
KeyModifierFlagssets up a new item to be added to the viewEnvironment. The extension toEnvironmentValueslets us store and retrieve the current flags from the environment.Finally there is the
ModifierFlagEnvironmentview. It has no content of its own - that is passed to the initializer in an@ViewBuilderfunction. What it does do is provide theStateObjectthat contains the state monitor, and it passes it's current value for the modifier flags into theEnvironmentof the content.To use the
ModifierFlagEnvironmentyou wrap a top-level view in your hierarchy with it. In a simple Cocoa app built from the default Xcode template, I changed the application SwiftUI content to be:So all of the views in the application could watch the flags.
Then to make use of it you could do:
Here the content view watches the environment for the flags and the view makes decisions on what to show using the current modifiers.