Join our newsletter! Get Swift & SwiftUI tips, project updates, and discounts on our books...JOIN OUR NEWSLETTER!Monthly Swift insights, updates, and deals...
Quick Tip Icon
Quick Tip

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.

It's common to reveal additional details and advanced settings when the user holds down the option key in a Mac app. Here is how we can use the new API to show a button only while the option modifier is pressed.

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)
        }
    }
}

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 coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • 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

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35