TweetFollow Us on Twitter

Drawers and Disclosure

Volume Number: 16 (2000)
Issue Number: 9
Column Tag: OS X

More or Less: Drawers and Disclosure Views for Cocoa

by Andrew C. Stone

In designing an intuitive interface for users, the great French architect Le Corbusier's adage still rings true: less is more. The less user interface you have visible, the more likely the user will be able to understand your program's feature set. But applications without depth and functionality are boring and leave the user feeling "if only the application could do X or Y". There are several ways to hide complexity and still have the features available for expert users. Along with the ubiquitous tabview, two major techniques are the drawer and the disclosure view.

Mac OS X introduces the concept of the drawer - a Daliesque subwindow which expands from under the parent window in a smooth opening animation, remaining attached to the window until no longer needed when it animates smoothly closed. An example of a good use of drawers is Mail.app's "Mailboxes". Drawers have certain limitations however - for instance, you cannot pull out a bottom-mounted drawer with a depth greater than the height of the window since this would violate the physical reality being emulated. Moreover, there were no drawers in Mac OS 9 or Mac OS X Server, so another technique, disclosure views must be used. The disclosure view, the little blue triangle that "shows more" by expanding the window to reveal more user interface, is one excellent technique. You can see this button in the standard Save Panel - which expands to show the file browser or collapses to present a very simple save interface. In this article, you will learn how to implement drawers and two types of disclosure views: one that expands the window to the right, and one that expands the window below.

<<ClosedDrawer.tiff This window presents a simplified interface for the user, with the drawer closed.>> <<ExpandedDrawer.tiff When the drawer is pulled out, additional options become available>>

Drawing Upon Drawers

The drawer is an instance of the NSDrawer object, a simple non-visual controller type object that acts as a coordinator. NSDrawer has a simple application programmer's interface (API) which allows you to specify the parent window, the content or container view which gets inserted into the drawer, the preferred edge from which the drawer expands, methods to programmatically open and close it, and a method to determine whether the drawer is open, closed, opening or closing. Moreover, there are optional delegate methods sent to the drawer's delegate and objects which register for drawer notifications before and after closing and opening and before resizing of the drawer. The full API is presented in /System/Library/Frameworks/AppKit.framework/Headers/NSDrawer.h.

InterfaceBuilder - the application to build graphical user interfaces via drag and drop of components - now has two ways to create drawers without writing a single line of code. From IB's Windows Palette, you can either drag out an NSDrawer object, and hook up the parent and content view yourself, or drag out a window with the drawer window already attached. The first method is excellent if you are modifying an existing interface, and the latter when you are designing from scratch.<<DrawersPalette.tiff: You can create completely functional drawers just by drag and drop from InterfaceBuilder>>.

I recommend that you create a new IB document and add a drawer/window combination to see how easy it is, and to learn a trick of the trade: the invisible box grouping technique. All visible objects in Cocoa are NSView subclasses, and they form a hierarchy that is rooted in the window's content view, the root enclosing view which contains everything in the window except the window controls and shadows. Because you cannot use IB to connect to this content view directly, you'll need to explicitly create a view which contains all of the user interface items that belong in the drawer. Select all the items and choose Layout -> Group in Box. Bring up the Inspector, and choose the Attributes pop-up menu item. Click on "No Title" and the no border icon - now you have an invisible containing view. If you click on the smaller drawer window created when you added the drawer/window combination, you see just such an invisible NSBox. Be sure to add your drawer components inside of this box by double-clicking it before dragging on new user interface elements.

Interface Builder allows you to specify the preferred edge from which the drawer should expand with the NSDrawer Inspector's Attributes sub-panel. For full control of the drawer's appearance and position, you may have to actually write a few lines of code, because some functionality is not yet fully exposed in Interface Builder. As of DP4, you need to set the drawer's delegate and size constraints programmatically. You can control the maximum and minimum size of the drawer, as well as the leading and trailing offsets. On a side mounted window, the leading offset is the height difference between the top of the drawer, and the top of the parent window's content view. Likewise, the trailing offset is the difference between the bottom of the drawer and the bottom of the parent window. All of the size constraints are mostly hints because there may be conflicting parameters.

Now that the drawer is configured, all that is required is to provide the user a means of opening and closing it. You need to have a button on the main window or a menu item which will expand the drawer when closed, and close it when open, simultaneously adjusting the text and/or icon on the button to synchronize with the drawer's state. Because the drawer can be in the act of opening or closing, you might want your button to do something only if it is actually closed or open, and just ignore clicks if the drawer is still animating between the open and closed state.

// given an instance variable "drawer" for the NSDrawer  and the sender is the button:

- (void)openOrCloseDrawer:(id)sender {
     if ([drawer state] == NSDrawerClosedState) {
	// tell the drawer to begin the opening animation:
		[drawer open:sender];
	// remember, not everyone speaks English! Code internationally:
		[sender setTitle:NSLocalizedStringFromTable(@"Less Options",@"CoolApp",
		@"title of drawer open and close button when the drawer is open")];
		[sender setImage:[NSImage imageNamed:@"OpenDrawer"];
    } else if ([drawer state] == NSDrawerOpenState) {
		[drawer close:sender];
		[sender setTitle:NSLocalizedStringFromTable(@"More Options",@"CoolApp",
		@"title of drawer open and close button when the drawer is closed")];
		[sender setImage:[NSImage imageNamed:@"CloseDrawer"];
    }
    // if it's in an opening or closing state, we'll ignore the click
}

As for initializing the drawer, you might want to do some of the following in the method that gets called by any object in an IB nib file after all the outlets are initialized, awakeFromNib:

- (void)awakeFromNib
{
  [drawer setLeadingOffset:10.];
  [drawer setTrailingOffset:40.];
  [drawer setContentSize:[rightBox frame].size];
  [drawer close:self];
  [drawer setDelegate:self];
  ...

Secret Disclosures

When a drawer is inappropriate because of size, backwards compatibility, or design issues, the classic disclosure view comes in handy. When disclosing additional user interface elements, the programmer is responsible for resizing the window and making sure everything fits correctly. All of this can be done easily using the technique of the invisible box as the top level container of the items in the standard window, and another invisible box as the top level container of the additional items which are presented when the window is expanded. The two most typical configurations are windows which expand to the right, and windows which expand below. We'll look at the expand to the right case first since it is simpler, because it does not involve moving the origin of the window. The underlying window display mechanism in the AppKit will automatically handle the cases where expanding the window would place part of the window off screen.

To understand the automatic resizing behavior of views (autosizing), it is helpful to look at InterfaceBuilder's Autosizing interface element of the Size Inspector. Each of the 6 possible stretch behaviors are represented graphically with rods and springs. A rod means "leave this dimension static" and a spring means "let this dimension fluctuate with the changing size of the window". <<StretchTheObject.tiff In this case, the object stretches and shrinks to fit into its containing view>> <<LeaveObjectRelativeToLowerRight.tiff Here, the object will remain in relative position to the lower right of its containing view.>>

Of course, you can set these all programmatically using NSView's -setAutosizing:(int)mask method by or'ing together the vertical and horizontal stretching behaviors: NSViewNotSizable, NSViewMinXMargin, NSViewWidthSizable, NSViewMaxXMargin, NSViewMinYMargin, NSViewHeightSizable andNSViewMaxYMargin.

Usually, you want the main items in the window to be resized when the user resizes the window - for example, a scrollable text view. In order that the disclosure view maintains the correct size whether it's showing or not, we'll approach the problem by always leaving the extra box in the window. When the extra box is hidden, the window will clip the box, when it's revealed, the window will be resized to contain it. This solves two problems: one, the extra items will be correctly freed when the window is released regardless of whether the extra items are showing, and two, the extra items will be correctly resized when the window is resized, even if they are not currently exposed.

In the following example, we have subclassed NSWindowController and placed the logic of resizing in the subclass controller. In InterfaceBuilder, the autosizing of the elements has been established, and we honor these settings by noting them at the beginning, and resetting them after resizing the window.

The button is set to be a two state "toggle" button, and we assign the images inside InterfaceBuilder in the Icon and Alternate Icon fields. By changing the state of the button, the icon automatically changes. This works with text as well by assigning an alternate title to the button, however, a down facing triangle image when the window is collapsed but can be expanded downward and an upward facing triangle image when it is expanded but can be collapsed works well.

// given: the controls to be displayed when the window expands are all inside
// an invisible NSBox named rightBox. The main controls are all inside a box named
// leftBox. The two boxes are laid out side by side in the window to fill the window's 
// contentView. Inside the left box, near the upper right is the two-state button whose
// target is the window controller with the action moreOrLessToTheRightAction:.

- (void)moreOrLessToTheRightAction:(id)sender
{
   NSWindow *win = [self window];
   NSRect winFrame = [win frame];
   NSRect rightFrame = [rightBox frame];

// get the original settings for reestablishing later:
   int leftMask = [leftBox autoresizingMask];
   int rightMask = [rightBox autoresizingMask];
   
// toggle the state
   int stateToSet = 1 - [sender tag];

// set the boxes to not automatically resize when the window resizes:
   [leftBox setAutoresizingMask:NSViewNotSizable];
   [rightBox setAutoresizingMask:NSViewNotSizable];

   // if the button's state is 1, then stateToSet == 0, let's collapse:
   if (stateToSet == 0) {
	    // reduce the desired size by the width of the right box:
        winFrame.size.width -= NSWidth(rightFrame);
   } else {
	   // increase the desired width by the width of the right box:
       winFrame.size.width += NSWidth(rightFrame);
    }

   // change the state of the button
   [sender setState:stateToSet];
   [sender setTag:stateToSet];

   // resize the window and display:
   [win setFrame:winFrame display:YES];

   // reset the boxes to their original autosize masks:
   [leftBox setAutoresizingMask:leftMask];
   [rightBox setAutoresizingMask:rightMask];
}

Adding a disclosure view which expands the window below is slightly more tricky because we'll have to move the origin of the window as we increase or decrease the height of the window so that the window keeps the title bar in the same location. Moreover, since origins begin at the bottom and move to positive Y upwards, we'll have to move the origins of the boxes as well.

- (IBAction)moreOrLessDownAction:(id)sender {
   NSWindow *win = [self window];
   NSRect winFrame = [win frame];

// we'll need to know the size of both boxes in this case:
   NSRect topFrame = [topBox frame];
   NSRect bottomFrame = [bottomBox frame];

// get the original settings for reestablishing later:
   int topMask = [topBox autoresizingMask];
   int bottomMask = [bottomBox autoresizingMask];
   
// toggle the state
   int stateToSet = 1 - [sender tag];

// set the boxes to not automatically resize when the window resizes:
   [topBox setAutoresizingMask:NSViewNotSizable];
   [bottomBox setAutoresizingMask:NSViewNotSizable];

   // if the button's state is 1, then stateToSet == 0, collapse it:
   if (stateToSet == 0) {
       // adjust the desired height and origin of the window:
        winFrame.size.height -= NSHeight(bottomFrame);
        winFrame.origin.y += NSHeight(bottomFrame);
	    // adjust the origin of the bottom box well below the window:
        bottomFrame.origin.y = -NSHeight(bottomFrame);
		// begin the top box at the bottom of the window
        topFrame.origin.y = 0.0;
   } else {
	   // stack the boxes one on top of the other:
       bottomFrame.origin.y = 0.0;
       topFrame.origin.y = NSHeight(bottomFrame);

       // adjust the desired height and origin of the window:
       winFrame.size.height += NSHeight(bottomFrame);
       winFrame.origin.y -= NSHeight(bottomFrame);
   }

   // adjust locations of the boxes:
   [topBox setFrame:topFrame];
   [bottomBox setFrame:bottomFrame];

   // change the state of the button to reflect new arrangement:
   [sender setState:stateToSet];
   [sender setTag:stateToSet];

  // resize the window and display:
   [win setFrame:winFrame display:YES];

   // reset the boxes to their original autosize masks:
   [topBox setAutoresizingMask:topMask];
   [bottomBox setAutoresizingMask:bottomMask];
}

Conclusion

With drawers and disclosure views, you have the tools and techniques to present simple and elegant interfaces, with more features available at the click of a button. InterfaceBuilder can provide almost all of the support necessary to fully implement drawers, and with just a few lines of code, your applications can take advantage of the powerful new features of Cocoa.


Andrew Stone <andrew@stone.com> is the chief executive haquer at Stone Design Corp <http://www.stone.com/> and divides his time between raising children, llamas & cane and writing applications for Mac OS X and playing with Darwin.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance 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
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.