Responding to keyboard modifiers on macOS in SwiftUI
New in macOS 15, we can now use onModifierKeysChanged(mask:initial:_:) to update our views when keyboard modifiers are held down.
On macOS, it is common to reveal additional details and advanced settings when the user holds down the option
key. Here is a view that shows a button to access advanced settings only while the user is holding down option
.
struct ContentView: View {
@State var optionPressed = false
var body: some View {
VStack(alignment: .trailing) {
Toggle("Show emoji", isOn: .constant(false))
Spacer()
if optionPressed {
Button("Advanced") {
/// TODO: open advance settings sheet
}
}
}
.onModifierKeysChanged(mask: .option) { old, new in
optionPressed = new.contains(.option)
}
}
}
![Screenshot macOS view showing the advanced button visible while the option key is held down.](/static/blog/RespondingToModifierKeys/settings.SdQXWMNtptPIIUxkp2WXSAqI17BfuVS_MRK-6dCHQj4.png)
The new onModifierKeysChanged()
method is only available on the latest macOS, so if you need to respond to modifier keys on iPadOS or older macOS versions, check out my other post Reading keyboard modifiers on iPad in SwiftUI.
![Swift Gems by Natalia Panferova book cover](/static/BookBanner/swift-gems/Book-cover.A8o9lklts3XSowuSdtbwm7nFGpx_86piXKVQDPjlGRQ.png)
![Swift Gems by Natalia Panferova book cover](/static/BookBanner/swift-gems/Book-cover-dark.Dzlxwf-Pl6V1PTgz7S3-tQmtANryxLfjru3mA7DDXnA.png)
Check out our new book!
Swift Gems
100+ tips to take your Swift code to the next level
Swift Gems
100+ tips to take your Swift code to the next level
- Advanced Swift techniques for experienced developers bypassing basic tutorials
- Curated, actionable tips ready for immediate integration into any Swift project
- Strategies to improve code quality, structure, and performance across all platforms
- Practical Swift insights from years of development, applicable from iOS to server-side Swift