How to make a keyboard shortcut to close dialog with Xcode/Interface Builder?

This seems awfully basic but here goes. If you are keyboard-oriented you get used to using Command-W to close windows all the time in OS X. I'd like to add that capability to the dialogs I am creating in Interface Builder for my program. I can see how to add a keyboard equivalent to a button action but what if I don't have a button?

Should I add an invisible button and put the shortcut on that? Seems clunky. Surely there is just some method I can override but what I've tried so far isn't working.


When you press Command + W, it's the exact same as choosing File -> Close from the menu bar. What Close does is send a performClose: message to the first responder. That, in turn, will check if the receiver or if the receiver's delegate implements windowShouldClose: , and the window will close if it returns YES (otherwise, it will call the close method).

So really, it depends on what type of dialog you've got here. If it's non-modal (essentially, if you can access the menu bar while it's running) and is an instance or subclass of NSWindow , then all you need to do is override the windowShouldClose: method in your dialog's delegate (or your dialog class, if you subclassed NSWindow or something) and make it return YES .

However , if the dialog is a modal dialog (you can't access the menu bar, switch windows, etc. while the dialog is running), then you can't do it this way. You could add an invisible button, but in all honesty, a modal dialog should not be closed by hitting Command-W , for that most certainly violates some Apple interface guideline out there. (Especially since, as Ande noted, it's standard practice to have Esc close/cancel a dialog.)


添加一个不可见的按钮工作得很好。


Is the dialog an NSWindow ? Because by default the File->Close menu option is set to the performClose: action of the first responder, and already wired to command-w

If the dialog isn't a window simply make your dialog first responder and implement the performClose: action.

链接地址: http://www.djcxy.com/p/19098.html

上一篇: 上传后iOS iOS UIImagePickerController结果图像方向

下一篇: 如何制作键盘快捷键来关闭Xcode / Interface Builder对话框?