Home > Articles > Programming > C/C++

The iOS 5 Developer's Cookbook: Working with View Controllers

This chapter shows how to build simple menus, create view navigation trees, design tab-bar-based and page-view-based applications using view-controller-based classes.
This chapter is from the book

View controllers simplify view management for many iOS applications. They allow you to build applications that centralize many tasks, including view management, orientation changes, and view unloading during low-memory conditions. Each view controller owns a hierarchy of views, which presents a complete element of a unified interface.

In the previous chapter, you built view-controller-based applications using Xcode and Interface Builder. Now it's time to take a deeper look at using view-controller-based classes and how to apply them to real-world situations for both iPhone/iPod and iPad design scenarios. In this chapter you discover how to build simple menus, create view navigation trees, design tab-bar-based and page-view-based applications, and more. This chapter offers hands-on recipes for working with a variety of controller classes.

Developing with Navigation Controllers and Split Views

The UINavigationController class offers one of the most important ways of managing interfaces on a device with limited screen space such as the iPhone and iPod touch. It creates a way for users to drill up and down a hierarchy of interface presentations to create a virtual GUI that's far larger than the device. Navigation controllers fold their GUIs into a neat tree-based scheme. Users travel through that scheme using buttons and choices that transport them around the tree. You see navigation controllers in the Contacts application and in Settings, where selections lead to new screens and "back" buttons move to previous ones.

Several standard GUI elements identify the use of navigation controllers in applications, as seen in Figure 5-1 (left). These include their large navigation bars that appear at the top of each screen, the backward-pointing button at the top-left that appears when the user drills into hierarchies, and option buttons at the top-right that offer other application functionality such as editing. Many navigation controller applications are built around scrolling lists, where elements in that list lead to new screens, indicated by grey and blue chevrons found on the right side of each table cell.

Figure 5-1

Figure 5-1 The iPhone's navigation controller uses chevrons to indicate that detail views will be pushed onscreen when their parents are selected. On the iPad, split view controllers use the entire screen, separating navigation elements from detail presentations.

The iPad, with its large screen size, doesn't require the kind of space-saving shortcuts that navigation controllers leverage on the iPhone and iPod touch, along with their cousins the tab view controller and modal view controller. iPad applications can use navigation controllers directly, but the UISplitViewController shown in Figure 5-1 (right) offers a presentation that's far better suited for the more expansive device.

Notice the differences between the iPhone implementation on the left and the iPad implementation on the right of Figure 5-1. The iPad's split view controller contains no chevrons. When items are tapped, their data appears on the same screen using the large right-hand detail area. The iPhone, lacking this space, presents chevrons that indicate new views will be pushed onscreen. Each approach takes device-specific design into account in its presentation.

Both the iPhone and iPad Inbox views use similar navigation controller elements, including the back button (iPad Book/Gmail for Book), an options button (Edit), and a status in the title bar (with its one unread message). Each of these elements is created using navigation controller API calls working with a hierarchy of e-mail accounts and mailboxes. The difference lies at the bottom of the navigation tree, at the level of individual messages that form the leaves of the data structure. On the iPhone, leaves are indicated by chevrons and, when viewed, are pushed onto the navigation stack, which accumulates the trace of a user's progress through the interface. On the iPad, leaves are presented in a separate view without those chevrons that otherwise indicate that users have reached the extent of the hierarchy traversal.

iPhone-style navigation controllers play roles as well on the iPad. When iPad applications use standard (iPhone-style) navigation controllers, they usually do so in narrow contexts such as transient popover presentations, where the controller is presented onscreen in a small view with a limited lifetime. Otherwise, iPad applications are encouraged to use the split view approach that occupies the entire screen.

Using Navigation Controllers and Stacks

Every navigation controller owns a root view controller. This controller forms the base of its stack. You can programmatically push other controllers onto the stack as the user makes choices while navigating through the model's tree. Although the tree itself may be multidimensional, the user's path (essentially his history) is always a straight line representing the choices already made to date. Moving to a new choice extends the navigation breadcrumb trail and automatically builds a back button each time a new view controller gets pushed onto the stack.

Users can tap a back button to pop controllers off the stack. The name of each button represents the title of the most recent view controller. As you return through the stack of previous view controllers, each back button previews the view controller that can be returned to. Users can pop back until reaching the root. Then they can go no further. The root is the root, and you cannot pop beyond that root.

This stack-based design lingers even when you plan to use just one view controller. You might want to leverage the UINavigationController's built-in navigation bar to build a simple utility that uses a two-button menu, for example. This would disregard any navigational advantage of the stack. You still need to set that one controller as the root via initWithRootViewController:. Storyboards simplify using navigation controllers for one- and two-button utilities, as you read about in Chapter 4, "Designing Interfaces."

Pushing and Popping View Controllers

Add new items onto the navigation stack by pushing a new controller with pushViewController:animated:. Send this call to the navigation controller that owns a UIViewController. This is normally called on self.navigationController when you're working with a primary view controller class. When pushed, the new controller slides onscreen from the right (assuming you set animated to YES). A left-pointing back button appears, leading you one step back on the stack. The back button uses the title of the previous view controller.

There are many reasons you'd push a new view. Typically, these involve navigating to specialty views such as detail views or drilling down a file structure or preferences hierarchy. You can push controllers onto the navigation controller stack after your user taps a button, a table item, or a disclosure accessory.

There's little reason to ever subclass UINavigationController. Perform push requests and navigation bar customization (such as setting up a bar's right-hand button) inside UIViewController subclasses. For the most part, you don't access the navigation controller directly. The two exceptions to this rule include managing the navigation bar's buttons and changing the bar's look.

You might change a bar style or its tint color by accessing the navigationBar property directly:

self.navigationController.navigationBar.barStyle =
    UIBarStyleBlackTranslucent;

To add a new button, you modify your navigationItem, which provides an abstract class that describes the content shown on the navigation bar, including its left and right bar button item and its title view. Here's how you can assign a button to the bar. To remove a button, assign the item to nil.

self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
    initWithTitle:@"Action" style:UIBarButtonItemStylePlain target:self
    action:)] autorelease];

Bar button items are not views. They are abstract classes that contain titles, styles, and callback information that are used by navigation items and toolbars to build actual buttons into interfaces. iOS does not provide you with access to the button views built by bar button items and their navigation items.

The Navigation Item Class

The objects that populate the navigation bar are put into place using the UINavigationItem class, which is an abstract class that stores information about those objects. Navigation item properties include the left and right bar button items, the title shown on the bar, the view used to show the title, and any back button used to navigate back from the current view.

This class enables you to attach buttons, text, and other UI objects into three key locations: the left, the center, and the right of the navigation bar. Typically, this works out to be a regular button on the right, some text (usually the UIViewController's title) in the middle, and a Back-styled button on the left. But you're not limited to that layout. You can add custom controls to any of these three locations You can build navigation bars with search fields, segment controls, toolbars, pictures, and more.

You've already seen how to add custom bar button items to the left and right of a navigation item. Adding a custom view to the title is just as simple. Instead of adding a control, assign a view. This code adds a custom UILabel, but this could be a UIImageView, a UIStepper, or anything else:

self.navigationItem.titleView = [[[UILabel alloc]
    initWithFrame:CGRectMake(0.0f,0.0f, 120.0f, 36.0f)] autorelease];

The simplest way to customize the actual title is to use the title property of the child view controller rather than the navigation item:

self.title = @"Hello";

When you want the title to automatically reflect the name of the running application, here is a little trick you can use. This returns the short display name defined in the bundle's Info.plist file. Limit using application-specific titles (rather than view-related titles) to simple utility applications.

self.title = [[[NSBundle mainBundle] infoDictionary]
    objectForKey:@"CFBundleName"];

Modal Presentation

With normal navigation controllers, you push your way along views, stopping occasionally to pop back to previous views. That approach assumes that you're drilling your way up and down a set of data that matches the tree-based view structure you're using. Modal presentation offers another way to show a view controller. After sending the presentModalViewController:animated: message to a navigation controller, a new view controller slides up into the screen and takes control until it's dismissed with dismissModalViewControllerAnimated:. This enables you to add special-purpose dialogs into your applications that go beyond alert views.

Typically, modal controllers are used to pick data such as contacts from the Address Book or photos from the Library or to perform a short-lived task such as sending e-mail or setting preferences. Use modal controllers in any setting where it makes sense to perform a limited-time task that lies outside the normal scope of the active view controller.

You can present a modal dialog in any of four ways, controlled by the modalTransitionStyle property of the presented view controller. The standard, UIModalTransitionStyleCoverVertical, slides the modal view up and over the current view controller. When dismissed it slides back down. UIModalTransitionStyleFlipHorizontal performs a back-to-front flip from right to left. It looks as if you're revealing the back side of the currently presented view. When dismissed, it flips back left to right. UIModalTransitionStyleCrossDissolve fades the new view in over the previous one. On dismissal, it fades back to the original view. Use UIModalTransitionStylePartialCurl to curl up content (in the way the Maps application does) to reveal a modal settings view "underneath" the primary view controller.

On the iPhone and iPod touch, modal controllers always fully take over the screen. The iPad offers more nuanced presentations. You can introduce modal items using three presentation styles. In addition to the default full-screen style (UIModalPresentationFullScreen), use UIModalPresentationFormSheet to present a small overlay in the center of the screen or UIModalPresentationPageSheet to slide up a sheet in the middle of the screen. These styles are best experienced in landscape mode to visually differentiate the page sheet presentation from the full-screen one.

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