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

The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »

Price Scanner via MacPrices.net

Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.