3

I'm trying to check whether or not shift is being pressed when a function is run. Something like this (but obviously not this, this is just an example):

func doThisThing() {
    if Keyboard.shared.keyBeingPressed(.shift) { // < What I'm trying to figure out
        print("Doing this thing.")
    } else {
        print("You're not holding shift.")
    }
}

I tried looking, but all I could find was keyDown/keyUp events, which isn't practical in this case.

Ben216k
  • 567
  • 4
  • 7
  • 1
    You shouldn't need to do such imperative things at all in SwiftUI, as far as I know... Or are you actually using AppKit and [tag:swiftui] is just a mistag? – Sweeper Nov 24 '21 at 20:16
  • If you _are_ using AppKit, see https://stackoverflow.com/a/14774656/5133585 – Sweeper Nov 24 '21 at 20:18
  • "all I could find was keyDown/keyUp events, which isn't practical in this case." what makes them impractical? – Alexander Nov 24 '21 at 20:22
  • Maintaining state for keyDown -> Up is not practical. In AppKit you override flagsChanged in your viewcontroller and it does that state management for you. I don't know how to do it in SwiftUI though. – hayesk Apr 02 '22 at 18:24

2 Answers2

2
import AppKit

public class KeyboardHelper
{
    public static var optionKeyIsDown: Bool
    {
        let flags = NSEvent.modifierFlags
        return flags.contains(.option)
    }

    public static var shiftKeyIsDown: Bool
    {
        let flags = NSEvent.modifierFlags
        return flags.contains(.shift)
    }
}
0

It's been a long time since I've done this sort of thing, but I seem to remember that you would need to set up an NSResponder and watch for keyDown/keyUp events. Then you'd parse the event to look for the shift key being pressed or released.

It looks like there is also a function flagsChanged that you can implement to be notified when one of the modifier keys changes state. See this SO thread:

How can I detect that the Shift key has been pressed?

Duncan C
  • 128,072
  • 22
  • 173
  • 272