Checking Modifier Keys in Swift

January 22nd, 2018

Filed under: Cocoa, Mac Development | Be the first to comment!

Checking for modifier keys (Command, Control, Option, and Shift) when handling events is different in Objective-C and Swift. In Objective-C you perform a bitwise AND operation to check if modifier keys were held down. In Swift you check if the event’s modifier flags contains the specific modifier key.

The following example demonstrates how to check the modifier keys for a mouse down event in Swift:

override func mouseDown(with event: NSEvent) {
    if event.modifierFlags.contains(.command) {
        // Handle command-click
    } 
    else if event.modifierFlags.contains(.control) {
        // Handle control-click
    }
    else {
        // Handle standard mouse click
    }
}
Facebooktwittergoogle_plusredditmail

Tags:


Leave a Reply

Your email address will not be published. Required fields are marked *