Custom Sheets don’t need their own xib files

9 08 2008

When you want to use custom sheets, Apple’s Documentation suggests that you create another xib file for the sheets(Using Custom Sheets).

But in fact, you don’t have to use a separate xib.

1. Create a controller class which handles both parent window and sheet window.

SheetTestController.h

@interface SheetTestController : NSObject {
	IBOutlet NSWindow *mainWindow;  //paent window
	IBOutlet NSWindow *sheetWindow; //sheet window
}

- (IBAction)showSheet:(id)sender; // open sheet on parent window
- (IBAction)closeSheet:(id)sender;// close sheet

@end

SheetController.m

@implementation SheetTestController

- (IBAction)showSheet:(id)sender
{
	[NSApp beginSheet: sheetWindow
	   modalForWindow: mainWindow
		modalDelegate: self
	   didEndSelector: @selector(didEndSheet:returnCode:contextInfo:)
		  contextInfo: nil];
}

- (IBAction)closeSheet:(id)sender
{
    [NSApp endSheet:sheetWindow];
}

- (void)didEndSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
    [sheet orderOut:self];
}

@end

2. Add “Show Sheet” button to parent window.

parentWindow

3. Add a sheet window, and put “close sheet” button on the window.

sheetWindow
make sure that “Visible At Launch” is unchecked.
sheetWindowAttributes

4. Add a SheetTestController object to the xib.

sheetControllerInstance

5. Connection settings of SheetTestController should be like this.

sheetControllerConnections

This is a little easier than “separate xib” way, but has disadvantages noted below.

  • increses memory usage because the sheet window always takes up some memory instead of instanciated only when necessary.
  • It’s difficult to use the sheet window from other xib files.