- (void) keyDown: (NSEvent *) event does not work

三世轮回 提交于 2019-12-24 04:13:26

问题


Below is the sample code.

- (void) keyDown: (NSEvent *) event
{
    NSString *chars = [event characters];
    unichar character = [chars characterAtIndex: 0];

    if (character == 27) {
        NSLog (@"ESCAPE!");
    }
} 

Should I need to set any delegate in InterfaceBuilder or any kinda binding??

Help Appreciated...


回答1:


keyDown needs to be overridden in an NSView subclass whose object is set as first responder. The responder chain should pass down the event, but to be sure you get it, make sure that your object is first responder.




回答2:


In cocoa only views participate in responder chain for this event. So you should override a some view method. The easy way is to find out what view is first responder for particular event you want to handle and use it.

window sends keyDown(with: ) stright to first responder which could handle it or pass up to responder chain. Not all views pass the events up. NSCollectionView doesn't pass the key event. It plays a bump sound instead.

It is also possible that a key you want to handle is a Key equivalent read more here. If so you should override performKeyEquivalent(with: ) method to receive this type of events instead. This events unlike keyDown events passed down from the window to the all subviews until someone handle them.

As mentioned NSCollectionView keyDown(with: ) method do not pass the key events up the responder chain. To handle such events in one of it's super views you should override it in collection view first and send event manually by calling self.nextResponder?.keyDown(with: event) for such events that you want to handle by yourself.



来源:https://stackoverflow.com/questions/1069433/void-keydown-nsevent-event-does-not-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!