开发者

Creating a window from a menu item

开发者 https://www.devze.com 2022-12-31 18:32 出处:网络
I would like three menu items on the menubar with the keyboard shortcuts cmd-1, cmd-2, cmd-3. This I know how to do.

I would like three menu items on the menubar with the keyboard shortcuts cmd-1, cmd-2, cmd-3. This I know how to do.

E开发者_如何学运维ach menu item would open up a different window (win1, win2, win3).

I want it so that only one instance of each window is permitted to be open at any one time (i.e. only one win1, one win2, etc).

How is this best approached?


If the windows in question are in the MainMenu.nib it's simple; attach the action to -makeKeyAndOrderFront: on each window.

If, on the other hand, they are not in MainMenu.nib, as is more likely the case if your application is structured in a sane fashion; things get a little more complicated. Long story short; you need to attach the menu item actions to appropriate methods on some manner of controller object (most likely your application delegate, although any controller that "sees" all the required nibs will do); and then have the controller in question send a similar message to its window.

This is generally a sensible approach, as you can have smaller controller objects attached to your windows that also act, if appropriate, as data sources for the various views in the windows in question.

It also allows for lazy loading of the windows, which is, at last count, a Good Thing™.

If this is some manner of document-oriented (not necessarily document-based) application, and the windows display some attribute of the currently selected "document" or piece of data; subclassing NSWindowController and loading the window controllers in your MainMenu.nib is probably a good place to start.

Note: If the objects responsible for controlling the windows live in the responder chain, they don't even need to be referenced in MainMenu.nib; you can just attach the appropriately-named IBActions (e.g. openDetailsWindow: or the like) used to open the windows to the virtual FirstResponder object. (Simply add the selectors to its list of known methods, and you're golden.)

Reedit: To make the window not appear in the windows menu, you can call [window setExcludedFromWindowsMenu:YES].

To check/uncheck the menu item is a bit tricker, as it requires your window controller actually knowing about the menu item; but as long as this is the case, it's quite simple, again; call -setState:, with the relevant state names (NSOffState, NSOnState), for example from the delegate methods called when the window is shown/closed. (This could, again, be encapsulated "inside" the application delegate; if you for whatever reason don't want your MainMenu.nib to contain the window controllers.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号