Skip to content

Instantly share code, notes, and snippets.

@Clarko
Last active March 28, 2023 18:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Clarko/a3b8d1484d4f466c6f4f0581164bee9a to your computer and use it in GitHub Desktop.
Save Clarko/a3b8d1484d4f466c6f4f0581164bee9a to your computer and use it in GitHub Desktop.
SwiftUI suppressible keyboard shortcuts
//
// RemovableKeyboardShortcut.swift
//
// Created by Clarko on 2/2/21.
//
// Adds an argument to dynamically remove a keyboard shortcut
//
import SwiftUI
extension View {
func keyboardShortcut(_ key: KeyEquivalent, disabled: Bool) -> some View {
self.modifier(RemovableKeyboardShortcut(key: key, disabled: disabled))
}
func keyboardShortcut(_ shortcut: KeyboardShortcut, disabled: Bool) -> some View {
self.modifier(RemovableKeyboardShortcut(shortcut: shortcut, disabled: disabled))
}
func keyboardShortcut(_ key: KeyEquivalent, modifiers: EventModifiers, disabled: Bool) -> some View {
self.modifier(RemovableKeyboardShortcut(key: key, modifiers: modifiers, disabled: disabled))
}
}
struct RemovableKeyboardShortcut: ViewModifier {
var shortcut: KeyboardShortcut? = nil
var key: KeyEquivalent? = nil
var modifiers: EventModifiers? = nil
var disabled: Bool
func body(content: Content) -> some View {
switch (shortcut, key, modifiers, disabled) {
case (let .some(shortcut), nil, nil, false):
content.keyboardShortcut(shortcut)
case (nil, let .some(key), nil, false):
content.keyboardShortcut(key)
case (nil, let .some(key), let .some(modifiers), false):
content.keyboardShortcut(key, modifiers: modifiers)
default:
content
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment