简体   繁体   中英

Adding a new window in Cocoa

I'm a beginner with Cocoa programming. All I wnated to know is how do I create a new window in Cocoa. I have created a NSViewController and window. As shown in tutorials I was able to add buttons to the MainMenu window and add actions to the buttons. Now I added a new NSViewController. I then went to plist file and made to load it first. My questions are as follows.

When adding a new NSViewController, hm and xib files were created but the XIB file just has custom window and no other control elements like minimize max buttons etc.

Secondly I added few elements and ran the file. The application ran but nothing was displayed on screen. Am I missing something.

You mostly only create a new NSWindowController if you add a new Nib-File.

The advantage of separating your windows or separate views in Nib-Files can be:

  1. Making your code more organized
  2. Easy instantiation of multiple windows of the same type (like browser windows)

If you don't need this, you can simply add a new window to your MainMenu.xib.
Then you can either let the window be visible at launch, or make an outlet to it and make it visible whenever you desire.


Otherwise you can go to your files -> Add new file -> Subclass of NSWindowController
There will be a checkbox to automatically create the xib-file for you, make sure to check.

Now just make sure to initialise with initWithWindowNibName: , and call showWindow: on it.

MyWindowControllerSubclass *wcs = [[MyWindowControllerSubclass alloc] initWithWindowNibName:@"TheNameOfMyNib"];
[wcs showWindow:self];

I was using XCode 4.2. Now I updated to 4.6.3. Now while creating NSWindowController xib file creating option is there. SO its done directly.

Otherwise you need to add a window controller and a new Window XIB. Later you can add an Object to properties tab. Then change the class to the Window Controller and link the Window to the Object.

If you want to add the view controller to a window then, it is fairly simple. NSViewController has a property named view. You would add this view to the window.contentView.

You would typically create a new xib file with a view and setting the file owner to your view controller. Then in the -(id)initWithNibName: method you could call the super with the nib name of your view to instantiate the controller with its view.

If you want to show a new window. Then create a new NSWindowController object and instantiate it, with the nib of your window and calling window on the controller should bring the window to front. If your window has already been initialised then, you could call methods like orderFront: , orderBack: on the window of the controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM