Reputation: 627
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.
Upvotes: 6
Views: 1633
Reputation: 216
Look in NSEvent.modifierFlags
:
let shiftIsPressed = NSEvent.modifierFlags.contains(.shift)
Upvotes: 1
Reputation: 145
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)
}
}
Upvotes: 4
Reputation: 131418
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?
Upvotes: 0