TweetFollow Us on Twitter

The Road to Code: Windows to the World

Volume Number: 25
Issue Number: 05
Column Tag: The Road to Code

The Road to Code: Windows to the World

Windows, Panels, and Sheets

by Dave Dribin

Introduction

We've seen and used windows before; every one of our GUI applications has used one. This month we're going to talk a little bit more about windows and some of their relatives: panels and sheets.

On screen, windows are represented by the NSWindow class. We've been creating windows by using Interface Builder. Both the MainMenu.xib for non-document based applications and MyDocument.xib for document-based applications contain an instance of NSWindow. For this article, let's start with a clean Cocoa application (not a document-based application).

The Cocoa application project template provides you with a MainMenu.xib that contains the main menu and the main window. Interface Builder allows you to configure several attributes for the window, and Figure 1 shows the attributes setup for the main window.


Figure 1: Main window attributes in Interface Builder

The most important attribute for our purposes has been Visible At Launch. This means that the window is automatically displayed on the screen when the nib file is loaded by the application. AppKit automatically loads MainMenu.nib when applications startup, so this is why our main window gets displayed when the application is run. For document-based applications, AppKit loads MyDocument.nib when a new document is created, again creating the document window. (Remember that .xib files are compiled into .nib files, and .nib files are stored in your application's bundle.)

Adding another window to our application is nearly as simple as dragging a new window from the Interface Builder Library into your application. I say "nearly" because the default options (as of Interface Builder version 3.1.1) are less than ideal. Open the MainMenu.xib file. In order to help reduce confusion between our two windows, rename the main window's title to Main Window, and drag a new window from the Library. Figure 2 shows the attributes for a new window dragged from the Library.


Figure 2: Default window attributes

Two checkboxes are different than our main window: Release When Closed and One Shot. What if, however, we do not want the window to be visible at launch, and we want to show the window programmatically? We need to uncheck Visible at Launch, but we should also uncheck Release When Closed. Otherwise, the NSWindow object gets released automatically when the window is closed, and any attempts to make the window visible again will cause a crash. This commonly trips people up, beginning and advanced programmers, alike. I almost never want the behavior of Release When Closed checked, but I sometimes forget to uncheck it.

The One Shot attribute is useful for windows that are not expected to be on screen all the time and are only displayed once or twice. This allows the system to free some of the window's resources when it's not visible. Let's check that one, too. And finally, change the title to New Window. The customized attributes for our new window are shown in Figure 3.


Figure 3: Customized window attributes

Let's add a button to the main window that, when clicked, will show this new window. Start by dragging a button to the main widow. We don't need any code to display the window as we can hookup the button to actions already defined on the NSWindow class. Control drag from the button to the window and set the action to makeKeyAndOrderFront:. This action method makes the window visible, if it is not already, and then makes it the front-most window.

So, what's with the strange method name, then? AppKit uses the term key window as the window that is currently receiving user input from the keyboard and mouse. There can only be one key window in an application. In fact, NSApplication has a method called keyWindow that returns the application's key window.

It's worth noting that one of the things you get "for free" when using AppKit is the Window menu you see in most applications. Along with the commands to minimize and zoom windows is a list of all windows in the application. AppKit automatically updates this list of windows. Thus, when we make our new window visible, the Window menu will get updated as shown in Figure 4.


Figure 4: Window menu

Panels

A panel is a special kind of window that is used mainly as an auxiliary window. Panels are represented in code using the NSPanel class, which is a subclass of NSWindow. Panels differ from windows in a few respects:

  • Panels are removed from the screen when the application is not active,
  • Panels do not get listed in the Window menu, and
  • Panels can by closed by pressing the Escape key.
  • Panels can also be configured to have utility style where it uses a smaller window bar and it floats above all other windows, even when it's not the key window.

Let's add a panel to our application to get a feel for how they work. Add another button to our main window with a title of Show Panel, as shown in Figure 5.


Figure 5: Show Panel button

Drag a panel from the Library window into your nib file, and switch to the Attributes tab. The default attributes for a panel are shown in Figure 6.


Figure 6: New panel attributes

By default, it's configured to use the Utility style. You can uncheck this if you want a panel to look more like a window, such as a standard Find panel. We're going to customize the rest of these attributes a bit. First, change the title to New Panel. Again, uncheck Release When Closed and Visible At Launch, and check One Shot. The customized panel attributes are shown in Figure 7.


Figure 7: Customized panel attributes

Finally, we need to hook the button up to the panel's makeKeyAndOrderFront: action by control dragging from the button to the panel. Run your application again and notice the difference between the new window and the new panel. Notice how the panel behaves differently than the windows and that it does not show in the Window menu.

Alerts

Sometimes you want to display a simple dialog box to the user to notify them of an event or ask a simple yes/no question. You could create and layout a new window every time you wanted to do this, but that is a bit of a hassle. Fortunately, AppKit provides alerts so you can easily provide simple dialog box-like windows. An example of an alert is shown in Figure 8.


Figure 8: Sample alert window

We do need to write code to demonstrate how to use alerts, so let's create an AppDelegate class. Add this action method to your AppDelegate

- (IBAction)showAlertWindow:(id)sender
{
    NSAlert * alert = [[[NSAlert alloc] init] autorelease];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert setMessageText:@"Message Text"];
    [alert setInformativeText:@"More detailed text."];
    [alert addButtonWithTitle:@"OK"];
    [alert addButtonWithTitle:@"Cancel"];
    
    NSInteger result = [alert runModal];
    if (result == NSAlertFirstButtonReturn)
        NSLog(@"OK pressed");
    else if (result == NSAlertSecondButtonReturn)
        NSLog(@"Cancel pressed");
}

The basic sequence for using alert windows is fairly simple. We need to create an instance of the NSAlert class, setup various parameters, and finally display it. There are three kinds of alert styles, and they represent the severity of the event you are trying to present to the user:

NSInformationalAlertStyle

NSWarningAlertStyle

NSCriticalAlertStyle

These can affect the icon used; for example, a critical alert will display an exclamation mark.

The message text is a short, one-line summary of the situation, for example, "Delete the record?" The informative text can be longer and more detailed, for example, "Deleted records cannot be restored. Are you sure you want to continue?"

You can add buttons to the alert, and they are added to the window from the right and going towards the left. Notice that the "OK" button was added first, and is furthest to the right. Also, the first button added is the default button and is assigned a key equivalent of Return. That's why it is blue in Figure 8. Any button named "Cancel" is assigned a key equivalent of Escape, as well.

With our alert all configured, it's time to display it with the runModal method. It does not return until the user presses a button, and returns the user's choice. It returns a constant based on which order the buttons were added; hence NSAlertFirstButtonReturn corresponds to the "OK" button in this example.

The runModal method displays the alert as a modal window. Modal means that the rest of the user interface is not accessible until the user responds to alert. This means the user cannot interact with any of the other windows or any of the menus. The user cannot even quit your application until they deal with the alert. This kind of behavior is generally frowned upon. You do not want to display modal dialog boxes very often because they disrupt the user's ability to use your application. Use them sparingly.

With our action written, switch to Interface Builder so we can hook it up to a button. We're going to need to instantiate the AppDelegate class and a new button, and then hook up the button to the showAlertWindow: action.

Alert Sheets

There is another variant of an alert that is less intrusive than modal windows called sheets. Sheets are attached to a specific window. When displayed, they animate down from the title bar. You can think of them as modal to a specific window. You cannot interact with the attached window until you respond to the sheet, however other windows and the menus remain responsive. An example of the same alert displayed as a sheet is shown in Figure 9. The sheet has the same information as the alert window, but it is now attached to the main window.


Figure 9: Sample alert sheet

Sheets are a little bit more complicated to use for a couple reasons. First, you need to attach a sheet to a specific window. We're going to use an outlet to the main window, but there are other ways you can get a reference to a window, depending on the situation. Second, displaying a sheet is a two-step process. Let's look at the code:

@synthesize mainWindow = _mainWindow;
- (IBAction)showAlertSheet:(id)sender
{
    NSAlert * alert = [[[NSAlert alloc] init] autorelease];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert setMessageText:@"Message Text"];
    [alert setInformativeText:@"More detailed text."];
    [alert addButtonWithTitle:@"OK"];
    [alert addButtonWithTitle:@"Cancel"];
    [alert beginSheetModalForWindow:_mainWindow
                      modalDelegate:self
                     didEndSelector:@selector(alertDidEnd:result:contextInfo:)
                        contextInfo:nil];
}
- (void)alertDidEnd:(NSAlert *)alert
             result:(NSInteger)result
        contextInfo:(void *)contextInfo
{
    if (result == NSAlertFirstButtonReturn)
        NSLog(@"OK pressed");
    else if (result == NSAlertSecondButtonReturn)
        NSLog(@"Cancel pressed");
    
}

The basic setup of the NSAlert object is the same; however, we display the sheet with the beginSheetModalForWindow:... method. This method takes several arguments because displaying a sheet asynchronous. This method returns right away and does not wait for the user to respond. Thus, we need to setup a delegate method that gets called when the user finally does respond.

The reason for the change in behavior as compared to runModal has to do with some details of how the AppKit event system is designed. The simple reason is that runModal blocks the entire application from running until the user responds, whereas a sheet only "blocks" a single window. All other windows need to respond normally. By returning just after the sheet is displayed, it allows the system to handle and respond to events for other windows.

The "did end" selector of the modal delegate works in a similar fashion to the target/action behavior of buttons and menus. The selector is called on the modal delegate object and can be named whatever you like. However it must take three arguments: the alert itself, the status, and the context info. The context info is the same as you passed into the beginSheet... method. You can use this to squirrel away some information that may not be available in instance variables.

To test this out, add yet another button to the main window and hook it up to this new action. You should see the sheet appear as shown in Figure 9 and you should see the log statements when the buttons are pressed.

Loading Windows from Nibs

Alerts are great for simple cases, but sometimes you need to create your own custom window. Perhaps you want a preferences window or an info panel or you want to have alerts with more controls on them. In these cases, you'll have to create your own windows, similar to what we did above. However, rather put all auxiliary windows in the main nib, you are better off putting them into their own separate nib. By doing this, you only load the windows as you need them, thus saving memory and resources by not creating windows you may never even display.

Let's go through the steps necessary to create and use a widow that is stored in its own nib. There is a class that's very handy for loading windows from a nib file called NSWindowController. While there are other ways of loading nib files (through NSNib and NSBundle), you should generally want to use a window controller as it takes care of some memory management issues for you. Subclassing NSWindowController also provides a place to put outlets and actions associated with that window.

Start by adding a new file your application. Under the Cocoa section, choose Objective-C NSWindowController subclass, as shown in Figure 10. Set the name of the new class to MyWindowController.


Figure 10: New NSWindowController subclass

We're going to add an action to our AppDelegate class to display a window. Make the header file match Listing 1.

Listing 1: AppDelegate.h

#import <Cocoa/Cocoa.h>
@class MyWindowController;
@interface AppDelegate : NSObject
{
    NSWindow * _mainWindow;
    MyWindowController * _myWindowController;
}
@property (nonatomic, retain) IBOutlet NSWindow * mainWindow;
- (IBAction)showAlertSheet:(id)sender;
- (IBAction)showAlertWindow:(id)sender;
- (IBAction)showWindowFromNib:(id)sender;
@end

I've added an instance variable for _myWindowController. I've also added a showWindowFromNib: action method. Now, let's jump to the implementation file and add the following method:

- (IBAction)showWindowFromNib:(id)sender
{
    if (_myWindowController == nil)
        _myWindowController = [[MyWindowController alloc] init];
    [_myWindowController showWindow:self];
}

You'll have to add an #import "MyWindowController.h" to the top of the file, too. What this does is create a new MyWindowController instance, if we don't already have one. This makes sure our nib is only loaded when it is actually needed. Creating windows like this saves memory and other resources.

The showWindow: method is a method of NSWindowController that shows its associated window. It's very similar to the makeKeyAndOrderFront: method we used earlier, but it takes care of loading the window from the nib and any other housekeeping tasks that need to be done before making the window key.

Back in Interface Builder, add another button to our main window titled Show Nib Window, as shown in Figure 11. Hook up this button's action to the showWindowFromNib: action on the AppDelegate.


Figure 11: Show Nib Window button

Now let's flesh out our window controller subclass. Make the MyWindowController.h file match Listing 2.

Listing 2: MyWindowController.h

#import <Cocoa/Cocoa.h>
@interface MyWindowController : NSWindowController
{
    NSButton * _sampleCheckbox;
}
@property (nonatomic) IBOutlet NSButton * sampleCheckbox;
- (IBAction)toggleCheckbox:(id)sender;
@end

We're going to add a checkbox to the window, so I went ahead and created an outlet for it. I also created an action for the checkbox. The MyWindowController.m file is shown in Listing 3.

Listing 3: MyWindowController.m

#import "MyWindowController.h"
@implementation MyWindowController
@synthesize sampleCheckbox = _sampleCheckbox;
- (id)init
{
    self = [super initWithWindowNibName:@"MyWindow"];
    return self;
}
- (IBAction)toggleCheckbox:(id)sender
{
    NSLog(@"Checkbox state: %d", [_sampleCheckbox state]);
}
@end

The outlet and action are fairly straight forward, and the only interesting bit is the constructor. We're calling NSWindowController's constructor and giving it the name of the nib to load.

Of course, this nib file doesn't exist yet, so let's create a new nib file with a window. You can do this in Xcode by using the New File... menu. Select the Window XIB file all the way at the bottom of the Cocoa section, as shown in Figure 12. Name the new file MyWindow.xib.


Figure 12: New Window XIB

Double click on the new MyWindow.xib file to open it up in Interface Builder so we can customize it. Before adding controls to our window, we should setup File's Owner to represent our window controller. File's Owner is a bit of an oddball object in the nib. It's not freeze dried in the nib like the other objects. It's the object responsible for cleaning up the nib when it's no longer needed and it usually loads the nib, too. By default, the File's Owner class is set to NSObject instance; however, we can customize this. Since the NSWindowController sets itself up to be the owner of the nib, we can change File's Owner to our subclass. Go to the Identity tab and change the class of the object to MyWindowController, as shown in Figure 13.


Figure 13: File's Owner class

This allows us to use File's Owner as a destination for outlets and actions. Resize the window and add a checkbox to it, as shown in Figure 14. Now let's setup the outlets. There are actually two outlets we need to setup. We've got the sampleCheckbox outlet that we created in our subclass, and this needs to be hooked up to the checkbox button. But NSWindowController has its own outlet called window. You need to hook this up so the window controller knows which window to open when showWindow: is called. Finally, hookup the action of the checkbox to the toggleCheckbox: action of File's Owner.


Figure 14: Nib window

We're almost done. We need to tweak the attributes of the window itself. Specifically, we need to uncheck Release On Closed and Visible At Launch and check the One Shot attributes. The window controller takes care of making the window visible, so we do not want it visible at launch. The rationale behind the other two attributes is the same as noted above.


Figure 15: Nib window attributes

And that should be all the changes we need. You should be able to run the application and view the new window. Listing 4 is the full code for the AppDelegate.m file.

Listing 4: AppDelegate.m

#import "AppDelegate.h"
#import "MyWindowController.h"
@implementation AppDelegate
@synthesize mainWindow = _mainWindow;
- (IBAction)showAlertSheet:(id)sender
{
    NSAlert * alert = [[NSAlert alloc] init];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert setMessageText:@"Message Text"];
    [alert setInformativeText:@"More detailed text."];
    [alert addButtonWithTitle:@"OK"];
    [alert addButtonWithTitle:@"Cancel"];
    [alert beginSheetModalForWindow:_mainWindow
                      modalDelegate:self
                     didEndSelector:@selector(alertDidEnd:result:contextInfo:)
                        contextInfo:nil];
}
- (void)alertDidEnd:(NSAlert *)alert
             result:(NSInteger)result
        contextInfo:(void *)contextInfo
{
    if (result == NSAlertFirstButtonReturn)
        NSLog(@"OK pressed");
    else if (result == NSAlertSecondButtonReturn)
        NSLog(@"Cancel pressed");
    
}
- (IBAction)showAlertWindow:(id)sender
{
    NSAlert * alert = [[[NSAlert alloc] init] autorelease];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert setMessageText:@"Message Text"];
    [alert setInformativeText:@"More detailed text."];
    [alert addButtonWithTitle:@"OK"];
    [alert addButtonWithTitle:@"Cancel"];
    
    NSInteger result = [alert runModal];
    if (result == NSAlertFirstButtonReturn)
        NSLog(@"OK pressed");
    else if (result == NSAlertSecondButtonReturn)
        NSLog(@"Cancel pressed");
}
- (IBAction)showWindowFromNib:(id)sender
{
    if (_myWindowController == nil)
        _myWindowController = [[MyWindowController alloc] init];
    [_myWindowController showWindow:self];
}
@end

Conclusion

As you can see, it's actually quite easy to display windows, even when using separate nib files. I highly recommend putting each window and panel in it's own nib file. Not only is it more memory efficient, but it also reduces the clutter of the nib. If you put all of your windows and panels in a single nib, it ends up getting confusing very quickly. Also using window controllers helps separate your code into more manageable chunks.

One thing I'm going to leave as an exercise for the reader is displaying custom sheets from a nib file. It turns out that you aren't limited to NSAlert for sheets. You can use any NSWindow as a sheet. You can use the beginSheet:... method of NSApplication. Read up on the Sheets Programming Topics for details on how to do this, which you can find on Apple's Developer Connection website or in the documentation included with Xcode.


Dave Dribin has been writing professional software for over eleven years. After five years programming embedded C in the telecom industry and a brief stint riding the Internet bubble, he decided to venture out on his own. Since 2001, he has been providing independent consulting services, and in 2006, he founded Bit Maki, Inc. Find out more at http://www.bitmaki.com/ and http://www.dribin.org/dave/.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.