How to activate different button behaviors when a modifier key is pressed
2024년 6월 21일About 2 min
How to activate different button behaviors when a modifier key is pressed 관련
SwiftUI by Example
Back to Home
How to activate different button behaviors when a modifier key is pressed | SwiftUI by Example
How to activate different button behaviors when a modifier key is pressed
Updated for Xcode 16
New in macOS 15
macOS often shows different button actions when the user holds down modifiers such as Command or Option, and we can get this in our own apps using the modifierKeyAlternate()
modifier.
Attach this modifier to a button, specifying which modifiers to watch for, and also what to show when those keys are pressed.
For example, we might make a button that shows a regular amount of detail normally, but when Option is held down it shows some extra detail:
Button("Show Details") {
print("Regular button action")
}
.modifierKeyAlternate(.option) {
Button("Show Verbose Details") {
print("Hold down Option to see this")
}
}
For extra power, you can use multiple modifierKeyAlternate()
modifiers to add different behaviors to different keys, or specify an array of keys to watch for several at once:
Button("Show Details") {
print("Regular button action")
}
.modifierKeyAlternate([.option]) {
Button("Show Verbose Details") {
print("Hold down option to see this")
}
}
.modifierKeyAlternate([.command, .option]) {
Button("Show Maximum Details") {
print("Hold down Command and Option to see this")
}
}
Similar solutions…
How to show a menu when a button is pressed | SwiftUI by Example
How to show a menu when a button is pressed
How to make buttons that repeat their action when pressed | SwiftUI by Example
How to make buttons that repeat their action when pressed
Customizing Button with ButtonStyle | SwiftUI by Example
Customizing Button with ButtonStyle
How to create a tappable button | SwiftUI by Example
How to create a tappable button
How to position and style subviews that come from a different view | SwiftUI by Example
How to position and style subviews that come from a different view