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

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 »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
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 below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

You can save $300-$480 on a 14-inch M3 Pro/Ma...
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
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer 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 MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.