Home > Articles > Web Development

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!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020