Home > Articles > Web Development

  • Print
  • + Share This
This chapter is from the book

Using Popovers with Toolbars

Popovers are used to display interface elements that configure how your application behaves but that don't need to be visible all the time. Our sample implementation will display a toolbar, complete with a Configure button, that invokes a popover. The popover will display configuration four switches (UISwitch) for a hypothetical time-based application: Weekends, Weekdays, AM, and PM.

The user will be able to update these switches in the popover, and then touch outside the popover to dismiss it. Upon dismissal, four labels in the main application view will be update to show the user's selections. The final application will resemble Figure 11.2.

Figure 11.2

Figure 11.2 This application will display a popover and update the main application view to reflect a user's actions in the popover.

Implementation Overview

The implementation of this project is simpler than it may seem at the onset. You'll be creating a View-based iPad application that includes a toolbar with the Configure button and four labels that will display what a user has chosen in the popover. The popover will require its own view controller and view. We'll add these to the main project, but they'll be set up almost entirely independently from the main application view.

Building the connection between the main view and the popover will require surprisingly few lines of code. We need to be careful that touching the Configure button doesn't continue to add popovers to the display if one is already shown, but you'll learn a trick that keeps it all under control.

Setting Up the Project

This project will start with the View-Based Application template; we'll be adding in another view and view controller to handle the popover. Let's begin. Launch Xcode (Developer/Applications), and then create a new View-based iPad project called PopoverConfig.

Xcode will create the basics structure for your project, including the PopoverConfigViewController classes. We'll refer to this as the main application view controller (the class the implements the view that the user sees when the application runs). For the popover content itself, we need to add a new view controller and XIB file to the PopoverConfig project.

Adding an Additional View Controller Class

With the Classes group selected in your Xcode project, choose File, New File, from the menu bar. Within the New File dialog box, choose the Cocoa Touch Class within the iPhone OS category, and then the UIViewController subclass icon, as shown in Figure 11.3.

Figure 11.3

Figure 11.3 Create the popover's content view controller and XIB file.

Be sure that Targeted for iPad and With XIB for user interface are selected, and then choose Next. When prompted, name the new class PopoverContentViewController and click Finish.

The PopoverContentViewController implementation and interface files are added to the Classes group.

Preparing the Popover Content

This hour's project is unique in that most of your interface work takes place in a view that is only onscreen occasionally when the application is running—the popover's content view. The view will have four switches (UISwitch), which we'll need to account for.

We only need to be able to read values from the popup view, not invoke any actions, so we'll just add four IBOutlets.

Adding Outlets

Open the PopoverContentViewController.h interface file and add outlets for four UISwitch elements: weekendSwitch, weekdaySwitch, amSwitch, pmSwitch. Be sure to also at @property directives for each switch. The resulting interface file is shown in Listing 11.1.

Listing 11.1.

#import <UIKit/UIKit.h>

@interface PopoverContentViewController : UIViewController {
    IBOutlet UISwitch *weekendSwitch;
    IBOutlet UISwitch *weekdaySwitch;
    IBOutlet UISwitch *amSwitch;
    IBOutlet UISwitch *pmSwitch;
}

@property (nonatomic,retain) UISwitch *weekendSwitch;
@property (nonatomic,retain) UISwitch *weekdaySwitch;
@property (nonatomic,retain) UISwitch *amSwitch;
@property (nonatomic,retain) UISwitch *pmSwitch;

@end

For each of the properties we've declared, we need to add a @synthesize directive in the implementation (popoverContentViewController.m) file. Open this file and make your additions following the @implementation line:

@synthesize weekdaySwitch;
@synthesize weekendSwitch;
@synthesize amSwitch;
@synthesize pmSwitch;

Setting the Popover Content Size

Our next step is easy to overlook, but amazingly important to the final application. For an application to present an appropriately sized popover, you must manually define the popover's content size. The easiest (and most logical) place to do this is within the popover's view controller.

Continue editing the popoverContentViewController.m file to uncomment its viewDidLoad method and add a size definition:

- (void)viewDidLoad {
    self.contentSizeForViewInPopover=CGSizeMake(320.0,200.0);
    [super viewDidLoad];
}

For this tutorial project, our popover will be 320 pixels wide and 200 pixels tall. Remember that Apple supports values up to 600 pixels wide and a height as tall as the iPad's screen area allows.

Releasing Objects

Even though this view controller sits outside of our main application, we still need to clean up memory properly. Finish up the implementation of the popoverContentViewController class by releasing the four switch instance variables in the dealloc method:

- (void)dealloc {
    [weekdaySwitch release];
    [weekendSwitch release];
    [amSwitch release];
    [pmSwitch release];
    [super dealloc];
}

That finishes the popoverContentViewController logic! Although we still have a little bit of work to do in Interface Builder, the rest of the programming efforts will take place in the main popoverConfig view controller class.

Preparing the View

Building a popover's view is identical to building any other view with one small difference: You can only use the portion of the view that fits within the size of the popover you're creating. Open the popoverContentViewController XIB file in Interface Builder and add four labels (Weekends, Weekdays, AM, and PM) and four corresponding switches (UISwitch) from the library.

Position these in the upper-left corner of the view to fit within the 320x200 dimensions we've defined, as shown in Figure 11.4.

Figure 11.4

Figure 11.4 Add four configuration switches and corresponding labels to the popover content view.

Connecting the Outlets

After creating the view, connect the switches to the IBOutlets. Control-drag from the File's Owner icon in the Document window to the first switch in the view (the Weekends switch in my implementation) and choose the weekendSwitch outlet when prompted, as shown in Figure 11.5.

Figure 11.5

Figure 11.5 Connect the switches to their outlets.

Repeat these steps for the other three switches, connecting them to the weekdaySwitch, amSwitch, and pmSwitch outlets.

The popover content is now complete. Let's move to the main application.

Preparing the Application View

With the popover content under control, we'll build out the main application view/view controller. There are only a few "gotchas" here, such as declaring that we're going to conform to the UIPopoverControllerDelegate protocol, and making sure that we create an instance of the popover content view.

Conforming to a Protocol

To conform to the popover controller delegate, open the popoverConfigViewController.h interface file, and modify the @interface line to include the name of the protocol, enclosed in <>. The line should read as follows:

@interface PopoverConfigViewController : UIViewController
<UIPopoverControllerDelegate> {

We still need to implement a method for the protocol within the view controller, but more on that a bit later.

Adding Outlets, Actions, and Instance Variables

We need to keep track of quite a few things within the main application's view controller. We're going to need an instance variable for the popover's controller (popoverController). This will be used to display the popover, and to check whether the popover is already onscreen. We'll also need an IBAction defined (showPopover) for displaying the popover.

In addition, five IBOutlets are required—four for UILabels that will display the values the user enters in the popover (weekdayOutput, weekendOutput, amOutput, pmOutput), and the last for the popover's view controller (popoverContent).

Sound like enough? Not quite! Because we're going to be using the popoverContentViewController class within the main application, we need to import its interface file, too.

Edit the interface file so that it matches Listing 11.2.

Listing 11.2.

#import <UIKit/UIKit.h>
#import "PopoverContentViewController.h"

@interface PopoverConfigViewController : UIViewController
           <UIPopoverControllerDelegate> {
    UIPopoverController *popoverController;
    IBOutlet    UILabel *weekdayOutput;
    IBOutlet    UILabel *weekendOutput;
    IBOutlet    UILabel *amOutput;
    IBOutlet    UILabel *pmOutput;
    IBOutlet    popoverContentViewController *popoverContent;
}

@property (retain,nonatomic) UILabel *weekdayOutput;
@property (retain,nonatomic) UILabel *weekendOutput;
@property (retain,nonatomic) UILabel *amOutput;
@property (retain,nonatomic) UILabel *pmOutput;
@property (retain,nonatomic) PopoverContentViewController *popoverContent;

-(IBAction)showPopover:(id)sender;

@end

For each @property directive, there needs to be a corresponding @synthesize in the popoverConfigViewController.m file. Edit the file now, adding these lines following the @implementation line:

@synthesize popoverContent;
@synthesize weekdayOutput;
@synthesize weekendOutput;
@synthesize amOutput;
@synthesize pmOutput;

This gives us everything we need to build and connect the main application interface elements, but before we do, let's make sure that everything we're added here is properly released.

Releasing Objects

Edit popoverConfigViewController.m's dealloc method to release the UILabels, and the instance of the popover content view controller (popoverContent):

- (void)dealloc {
    [weekdayOutput release];
    [weekendOutput release];
    [amOutput release];
    [pmOutput release];
    [popoverContent release];
    [super dealloc];
}

Nicely done! All that's left now is to edit the popoverConfigViewController XIB file to create the main application interface and write the methods for showing and handling the subsequent dismissal of the popover.

Creating the View

Open the popoverConfigViewController XIB file in Interface Builder. We need to add a toolbar, a toolbar button, and some labels to display our application's output. Let's start with the labels, because we've got plenty of experience with them. Drag a total of eight UILabel objects to the screen. Four will hold the application's output, and four will just be labels (fancy that!).

Arrange the labels near the center of the screen, forming a column with Weekends:, Weekdays:, AM:, and PM: on the left, and On, On, On, On aligned with them on the right. The On labels are the labels that will map to the IBOutlet output variables; they've been set to a default value of On because the switches in the popover content view default to the On position.

If desired, use the Attributes Inspector (Command+1) to resize the labels to something a bit larger than the default. I've used a 48pt font in my interface, as shown in Figure 11.6.

Figure 11.6

Figure 11.6 Add a total of eight labels to the view.

Adding a Toolbar and Toolbar Button

Using the Interface Builder Library, drag an instance of a toolbar (UIToolbar) to top of the view. The toolbar object includes, by default, a single button called Item. Double-click the button to change its title to Configure; the button will automatically resize itself to fit the label.

In this application, the single button is all that is needed. If your project needs more, you can drag Bar Button Items from the library into the toolbar. The buttons are shown as subviews of the toolbar within the Interface Builder Document window.

Figure 11.7 shows the final interface and the Document window showing the interface hierarchy.

Figure 11.7

Figure 11.7 Labels, and toolbar, and a toolbar button complete the interface.

Connecting the Outlets and Actions

It's time to connect the interface we've built to the outlets and actions we defined in the view controller. Control-drag from the File's Owner icon in the IB Document window to the first On label, connecting to the weekendOutput outlet, as shown in Figure 11.8. Repeat for the other three labels, connecting to weekdayOutput, amOutput, and pmOutput.

Figure 11.8

Figure 11.8 Connect each output label to its outlet.

Next, Control-drag from the Configure toolbar button to the File's owner icon. Choose showPopover when prompted, as shown in Figure 11.9. Note that we didn't have to worry about connecting from a Touch Up Inside event because toolbar buttons have only one event that can be used.

Figure 11.9

Figure 11.9 Connect the configure button to the action.

Only one step remains to be completed in interface builder: instantiating the popover content view controller.

Instantiating the Popover Content View Controller

Earlier in the tutorial, we developed the popover content view controller and view (popoverContentViewController). What we haven't done, however, is actually use it anywhere. We can take two approaches to creating an instance of the controller so that we can use it in the application:

  1. The content view controller is instantiated whenever the popover is invoked, and released when the popover is dismissed.
  2. The content view controller is instantiated when main application view loads and is released when the application is finished.

I've chosen to go with approach number 2. By instantiating the popover's view controller when the main application view loads, we can use it repeatedly without reloading the view. This means that if the user displays the popover and updates the switches, those changes will be visible no matter how many times the user dismisses or opens the popover.

Without adding any code, we can instantiate popoverContentViewController when the popoverConfigViewController.xib file is loaded:

  1. Open the popoverConfigViewController.xib file's document window in Interface Builder.
  2. Drag a View Controller object from the Library into the document window.
  3. Select the view controller in the Document window, and press Command+4 to open the Identity Inspector.
  4. Set the class to the popoverContentViewController rather than the generic UIViewController class set by default. This can be seen in Figure 11.10.
    Figure 11.10

    Figure 11.10 Set the object to be an instance of .

  5. Switch to the Attributes Inspector (Command+1) and set the NIB name field to popoverContentViewController so that the view controller knows where its view is stored.
  6. Close the Inspector window.
  7. Control drag from the File's Owner icon to the popover content view controller icon within the Document window. Choose popoverContent when prompted, as shown in Figure 11.11.
    Figure 11.11

    Figure 11.11 Connect the popover content view controller to the outlet.

  8. Save the XIB file.

Our views and view controllers are completed. All that remains is writing the code that handles the application logic.

Implementing the Application Logic

We need to implement two methods to complete this tutorial. First, we need to implement showPopover to display the popover and allow the user to interact with it. Second, the popover controller delegate method popoverControllerDidDismissPopover must be built to take care of cleaning up the popover when the user is done with it, and to update the application's view with any changes the user made within the popover.

Displaying the Popover

Open the popoverConfigViewController.m file and add the showPopover method, shown in Listing 11.3, immediately following the @synthesize directives.

Listing 11.3.

1: -(IBAction)showPopover:(id)sender {
2:     if (popoverController==nil) {
3:         popoverController=[[UIPopoverController alloc]
4:             initWithContentViewController:popoverContent];
5:         [popoverController presentPopoverFromBarButtonItem:sender
6:          permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
7:         popoverController.delegate=self;
8:     }
9: }

There are three steps to displaying and configuring the popover.

First, in lines 3–4, the popover controller, popoverController, is allocated and initialized with the popover's content view, popoverContent.

Second, lines 5 and 6 display the popover using the (very verbose) method presentPopoverFromBarButtonItem:permittedArrowDirections:animated. The bar button item (our toolbar button) can be referenced through the sender variable, which is passed to showPopover when the button is pressed. The permittedArrowDirections parameter is passed the constant UIPopoverArrowDirectionAny, meaning the popover can be drawn with an arrow that points in any direction (as long as it points to the specified interface element). The animated parameter gives the iPad the go-ahead to animate the appearance of the popover (currently a nice fade-in effect).

Third, line 7 sets the popover controller's delegate to the same object that is executing the code (self)—in other words, the popoverConfigViewController. By doing this, the popover controller will automatically call the method popoverControllerDidDismissPopover within popoverConfigViewController.m when the user is done with it.

Nothing too scary, right? Right. But what about lines 2 and 8? The entire display of the popover is wrapped in an if-then statement. The reason for this can be easily demonstrated by removing the if-then and running the application. Without the conditional, multiple copies of the popover will be displayed (one on top of the other) each time the Configure button is pressed. This is a large memory leak and would make the application behave very strangely for the user. To get around the problem, we perform a simple comparison: popoverController==nil. When the popover controller hasn't been initialized, it will have a value of nil (that is, no value at all). In this case, the statements to initialize the controller and show the popover are executed. Once the popover is displayed, however, the popoverController has a value and will no longer equal nil, keeping any further instances of it from being displayed.

Of course, we want the user to be able to dismiss and redisplay the popover, so we need to release the popoverController and set it back to nil when we hide the popover again. Let's look at that implementation now.

Reacting to the Popover Dismissal

When the user gets rid of the popover by touching outside of its content area, we want our application to react and display any changes the user made within the popover view. We also want to prepare the popover's controller to show the popover again. Enter the popover controller delegate method popoverControllerDidDismissPopover as shown in Listing 11.4.

Listing 11.4.

 1: -(void)popoverControllerDidDismissPopover:
 2:               (UIPopoverController *)controller {
 3:     weekdayOutput.text=@"On";
 4:     weekendOutput.text=@"On";
 5:     amOutput.text=@"On";
 6:     pmOutput.text=@"On";
 7:
 8:     if (!popoverContent.weekdaySwitch.on) {
 9:         weekdayOutput.text=@"Off";
10:     }
11:     if (!popoverContent.weekendSwitch.on) {
12:         weekendOutput.text=@"Off";
13:     }
14:     if (!popoverContent.amSwitch.on) {
15:         amOutput.text=@"Off";
16:     }
17:     if (!popoverContent.pmSwitch.on) {
18:         pmOutput.text=@"Off";
19:     }
20:     [popoverController release];
21:     popoverController=nil;
22: }

Most of the display logic used in this method should be familiar to you by now. Lines 3–6 set the four output labels to On, because this is the default state of our switches. Lines 8–19 are simple if-then statements which check to see whether a switch is not set to on, and, if so, sets the corresponding output label to Off.

Because we have an instance variable for the popover's view controller (popoverContent) and have defined the UISwitches as properties, we can access the individual state of a given switches using its on property in a single line: popoverContent.<switch instance variable>.on.

In the final two lines, 20 and 23, the popover controller is released and its instance variable (popoverController) set to nil. This prepares it for the next time the user presses the Configure button.

The application is now complete. Use Build and Run to test the popover's display on your iPad. You've just implemented one of the most important and flexible UI features available on the iPad platform!

  • + Share This
  • 🔖 Save To Your Account