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.
Asked
Active
Viewed 2,095 times
3

glenstorey
- 5,134
- 5
- 39
- 71
2 Answers
7
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.
}
}

glenstorey
- 5,134
- 5
- 39
- 71
-
2For me, just `event.charactersIgnoringModifiers == String(UnicodeScalar(NSDeleteCharacter)!)` works. I am using Swift 5.1. – Ram Patra May 25 '20 at 16:49
2
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?

Ken Thomases
- 88,520
- 7
- 116
- 154
-
Wow - this sounds much better. I can't override any method called delete, but there is a `deleteBackward`. The app is based around a `NSStatusBarWindow` with no dock icon, so we don't actually implement a edit menu at the moment - is this a requirement? – glenstorey Feb 22 '16 at 16:53
-
Well, if you don't already have an Edit menu, then this approach is probably not any easier than others. You could arrange to provide such a (perhaps hidden) menu, but it ends up being more complicated. – Ken Thomases Feb 22 '16 at 19:50
-