Detect when delete key pressed on control

2.1k views Asked by At

How can I subclass a NSControl object (such as a NSImageView) to detect the press of the delete key? Specifically I want to clear an image from a NSImageView, but there are probably wider applications.

2

There are 2 answers

1
glenstorey On

Subclass the NSControl and override the keyDown function. Use NSEvent.charactersIgnoringModifiers to check against the unicode value of NSDeleteCharacter.

    override func keyDown(theEvent: NSEvent) {
        //From Apple sample code: https://developer.apple.com/library/ios/samplecode/Lister/Listings/Swift_ListerOSX_ListViewController_swift.html
        if theEvent.charactersIgnoringModifiers == String(Character(UnicodeScalar(NSDeleteCharacter))) {
            //Take action. 

        }
     }
3
Ken Thomases On

It should work to just implement the -delete: action method, which is what the Delete item of the Edit menu sends to the responder chain. That way, it works not just for the Delete key but for all other ways of invoking that menu item (mouse, putting focus on the menus and navigating by arrow keys, accessibility technologies, etc.).

In fact, NSImageView already implements -delete:, so are you sure you have to do anything?