Chapter 6. Multiview Applications

Up until this point, we've written applications with a single view controller. While there certainly is a lot you can do with a single view, the real power of the iPhone platform emerges when you can switch out views based on user input. Multiview applications come in several different flavors, but the underlying mechanism is the same, regardless of how it may appear on the screen.

Strictly speaking, we have worked with multiple views in our previous applications, since buttons, labels, and other controls are all subclasses of UIView and can all go into the view hierarchy. But when Apple uses the term "view" in documentation, it is generally referring to a UIView or one of its subclasses that have a corresponding view controller. These types of views are also sometimes referred to as content views, because they are the primary container for the content of our application.

The simplest example of a multiview application is a utility application. A utility application focuses primarily on a single view but offers a second view that can be used to configure the application or to provide more detail than the primary view. The Stocks application that ships with iPhone is a good example (see Figure 6-1). If you click the little i icon in the lower-right corner, the view flips over to let you configure the list of stocks tracked by the application.

The Stocks application that ships with iPhone has two views, one to display the data and another to configure the stock list.

Figure 6.1. The Stocks application that ships with iPhone has two views, one to display the data and another to configure the stock list.

There are also several tab bar applications that ship with the iPhone, such as the Phone application (see Figure 6-2) and the Clock application. A tab bar application is a multiview application that displays a row of buttons, the tab bar, at the bottom of the screen. Tapping one of the buttons causes a new view controller to become active and a new view to be shown. In the Phone application, for example, tapping Contacts shows a different view than the one shown when you tap Keypad.

Note

Tab bars and toolbars can be confusing. A tab bar is used for selecting one and only one option from among two or more. A toolbar can hold buttons and certain other controls, but those items are not mutually exclusive. Figure 6-3 shows a toolbar at the bottom of the iPhone screen. Figure 6-4 shows a tab bar at the bottom of the iPhone screen. In practical application, the tab bar is almost always used to select between two or more content views, while the toolbar is usually used to display buttons for doing common tasks.

Another common kind of multiview iPhone application is the navigation-based application, which uses a navigation controller to present hierarchical information to the user. The Mail application is a good example (see Figure 6-3). In Mail, the first view you get is a list of your mail accounts. Touching one of those takes you into a list of your folders. Touching a folder shows you the e-mail messages in that folder, and touching the e-mail message shows you the content of the message. A navigation-based application is useful when you want to present a hierarchy of views.

Because views are themselves hierarchical in nature, it's even possible to combine different mechanisms for swapping views within a single application. For example, the iPhone's iPod application uses a tab bar to switch between different methods of organizing your music and a navigation controller and its associated navigation bar to allow you to browse your music based on that selection. In Figure 6-4, the tab bar is at the bottom of the screen, and the navigation bar is at the top of the screen.

Each of these types of multiview application uses a specific controller class from the UIKit. Tab bar interfaces are implemented using the class UITabBarController and navigation interfaces using UINavigationController. In this chapter, we're going to focus on the structure of multiview applications and the basics of swapping content views by building our own multiview application from scratch. We will write our own custom controller class that switches between two different content views, which will give you a strong foundation for taking advantage of the various multiview controllers that Apple provides.

The Phone application is an example of a multiview application using a tab bar.

Figure 6.2. The Phone application is an example of a multiview application using a tab bar.

The iPhone Mail application is an example of a multiview application using a navigation bar.

Figure 6.3. The iPhone Mail application is an example of a multiview application using a navigation bar.

The iPod application uses both a navigation bar and a tab bar.

Figure 6.4. The iPod application uses both a navigation bar and a tab bar.

The View Switcher Application

The application we're going to build in this chapter, View Switcher, is fairly simple in appearance, but in terms of the code we're going to write, it's by far the most complex application we've tackled. View Switcher will consist of three different controllers, three nibs, and an application delegate.

When first launched, View Switcher will look like Figure 6-5, with a toolbar at the bottom containing a single button. The rest of the view will contain a blue background and a button yearning to be pressed.

When the Switch Views button is pressed, the background will turn yellow, and the button's title will change (see Figure 6-6).

If either the Press Me or Press Me, Too button is pressed, an alert will pop up indicating which view's button was pressed (see Figure 6-7).

Although we could achieve this same functionality by writing a single-view application, we're taking this more complex approach to demonstrate the mechanics of a multiview application. There are actually three view controllers interacting in this simple application: one that controls the blue view, one that controls the yellow view, and a third special controller that swaps the other two in and out when the Switch Views button is pressed.

View Switcher at launch

Figure 6.5. View Switcher at launch

After pressing the Switch Views button

Figure 6.6. After pressing the Switch Views button

Pressing the center button shows an alert.

Figure 6.7. Pressing the center button shows an alert.

The Architecture of a Multiview Application

Before we start building our application, let's talk a little bit about the way iPhone multiview applications are put together. Nearly all multiview applications use the same basic pattern.

The nib file is a key player here. In a bit, when you create the View Switcher project, you'll find the file MainWindow.xib in your project window's Resources folder. Inside the file, you'll find the application delegate and the application's main window, along with the File's Owner and First Responder icons. We'll add an instance of a controller class that is responsible for managing which other view is currently being shown to the user. We call this controller the root controller because it is the first controller the user sees and the controller that is loaded when the application loads. This root controller is often an instance of UINavigationController or UITabBarController, though it can also be a custom subclass of UIViewController. In a multiview application, the job of the root controller is to take two or more other views and present them to the user as appropriate, based on the user's input. A tab bar controller, for example, will swap in different views and view controllers based on which tab bar item was last tapped. A navigation controller will do the same thing as the user drills down and backs up through hierarchical data.

Note

The root controller is the primary view controller for the application and, as such, is the view that specifies whether it is OK to automatically rotate to a new orientation, though the root controller can pass responsibility for things like that to the currently active controller.

In multiview applications, most of the screen will be taken up by a content view, and each content view will have its own controller with its own outlets and actions. In a tab bar application, for example, taps on the tab bar will go to the tab bar controller, but taps anywhere else on the screen will go to the controller that corresponds to the content view currently being displayed.

Anatomy of a Content View

In a multiview application, each view controller controls a content view, and these content views are where the bulk of your application's user interface gets built. Each content view generally consists of up to three pieces: the view controller, the nib and a subclass of UIView. Unless you are doing something really unusual, your content view will always have an associated view controller, will usually have a nib, and will sometimes subclass UIView. Although you can create your interface in code rather than using a nib file, few people choose that route because it is more time consuming and more difficult to maintain.

In this chapter, we'll only be creating a nib and a controller class for each content view.

In the View Switcher project, our root controller controls a content view that consists of a toolbar that occupies the bottom of the screen. The root controller then loads a blue view controller, placing the blue content view as a subview to the root controller view. When the root controller's switch views button is pressed (the button is in the toolbar), the root controller swaps out the blue view controller and swaps in a yellow view controller, instantiating it if it needs to do so. Confused? Don't worry, because this will become clearer as you walk through the code.

Building View Switcher

Enough theory! Let's go ahead and build our project. Select New Project... from the File menu, or press

Building View Switcher
Selecting a new project template

Figure 6.8. Selecting a new project template

The template we just selected is actually even simpler than the one we've been using up to now. This template will give us a window, an application delegate, and nothing else—no views, no controllers, no nothing. You won't use this template very often when you're creating applications, but by starting from nothing, you'll really get a feel for the way multiview applications are put together.

Take a second to expand the Resources and Classes folders in the Groups & Files pane and look at what's there. You'll find a single nib file, MainWindow.xib; the View_Switcher-Info.plist file; and the two files in the class folder that implement the application delegate. Everything else we need for our application, we will have to create.

Creating Our View Controller and Nib Files

One of the more daunting aspects of creating a multiview application from scratch is that we have to create several interconnected objects. We're going to create all the files that will make up our application before we do anything in Interface Builder and before we write any code. By creating all the files first, we'll be able to use Xcode's Code Sense to write our code faster. If a class hasn't been declared, Code Sense has no way to know about it, so we would have to type it in full every time, which takes longer and is more error prone.

Fortunately, in addition to project templates, Xcode also provides file templates for many standard file types, which makes creating the basic skeleton of our application fairly easy. Single-click the Classes folder in the Groups & Files pane, and then press

Creating Our View Controller and Nib Files
Creating a new view controller class

Figure 6.9. Creating a new view controller class

If you select Cocoa Touch Class from the left-hand pane, you will be given templates for a number of common Cocoa Touch classes. Select UIViewController subclass. In the lower-right pane, you'll see a checkbox labeled With XIB for user interface. If that box is checked, click it to uncheck it. If you select that option, Xcode will also create a nib file that corresponds to this controller class. We will start using that option in the next chapter, but for now, we want you to see how the different parts of the puzzle fit together by creating them all individually.

Click Next. Then type in the name SwitchViewController.m, and make sure that Also create "SwitchViewController.h" is checked before clicking the Finish button. Xcode should add two files to your Classes folder; the SwitchViewController class will be your root controller that swaps the other views in and out. Repeat the same steps two more times to create BlueViewController.m and YellowViewController.m, making sure to also create the corresponding header files for both. These are the two content views that will get swapped in and out by SwitchViewController.

We also need two more nib files, one for each of the two content views we just created. To create these, single-click the Resources folder in the Groups & Files pane so that we create them in the correct place, and then press

Creating a new view controller class
Creating nib files for the content views

Figure 6.10. Creating nib files for the content views

Select the icon for the View XIB template, which will create a nib with a content view, and then click the Next button. When prompted for a filename, type BlueView.xib. Repeat the steps to create a second nib file called YellowView.xib. Once you've done that, you have all the files you need. It's time to start hooking everything together.

Modifying the App Delegate

Our first stop on the multiview express is the application delegate. Single-click the file View_SwitcherAppDelegate.h in the Groups & Files pane, and make the following changes to that file:

#import <UIKit/UIKit.h>
@class SwitchViewController;
@interface View_SwitcherAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    SwitchViewController *switchViewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet SwitchViewController
    *switchViewController;
@end

The IBOutlet declaration you just typed is an outlet that will point to our application's root controller. We need this outlet because we are about to write code that will add the root controller's view to our application's main window when the application launches. By doing that, when we go to Interface Builder and add an instance of the SwitchViewController class to MainWindow.xib, we'll already have an outlet to connect it to.

Now, we need to add the root controller's view to our application's main window. Click View_SwitcherAppDelegate.m, and add the following code:

#import "View_SwitcherAppDelegate.h"
#import "SwitchViewController.h"
@implementation View_SwitcherAppDelegate

@synthesize window;
@synthesize switchViewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    // Override point for customization after application launch
    [window addSubview:switchViewController.view];
    [window makeKeyAndVisible];
}

- (void)dealloc {
    [window release];
    [switchViewController release];
    [super dealloc];
}
@end

Besides implementing the switchViewController outlet, we are adding the root controller's view to the window. Remember, the window is the only gateway to the user, so anything that needs to be displayed to the user has to get added as a subview of the application's window.

SwitchViewController.h

Because we're going to be adding an instance of SwitchViewController to MainWindow.xib, now is the time to add any needed outlets or actions to the SwitchViewController.h header file.

We'll need one action method to toggle between the two views. We won't need any outlets, but we will need two other pointers, one to each of the view controllers that we're going to be swapping in and out. These don't need to be outlets, because we're going to create them in code rather than in a nib. Add the following code to SwitchViewController.h:

#import <UIKit/UIKit.h>

@class BlueViewController;
@class YellowViewController;

@interface SwitchViewController : UIViewController {
    YellowViewController *yellowViewController;
    BlueViewController *blueViewController;
}
@property (retain, nonatomic) YellowViewController *yellowViewController;
@property (retain, nonatomic) BlueViewController *blueViewController;

-(IBAction)switchViews:(id)sender;
@end

Now that we've declared the action we need, we can add an instance of this class to MainWindow.xib.

Modifying MainWindow.xib

Save your source code, and double-click MainWindow.xib to open it in Interface Builder. Four icons should appear in the nib's main window: File's Owner, First Responder, View_SwitcherAppDelegate, and Window (see Figure 6-11). We need to add one more icon that will represent an instance of our root controller. Since Interface Builder's library doesn't have a SwitchViewController, we'll have to add a view controller and change its class to SwitchViewController.

Since the class we need to add is a subclass of UIViewController, look in the library for View Controller (see Figure 6-12), and drag one to the nib's main window (the window with the icons and the title MainWindow.xib).

MainWindow.xib

Figure 6.11. MainWindow.xib

View Controller in the library

Figure 6.12. View Controller in the library

Once you do this, your nib's main window will now have five icons, and a new window containing a dashed, gray, rounded rectangle labeled View should appear (see Figure 6-13).

The window representing your view controller in Interface Builder

Figure 6.13. The window representing your view controller in Interface Builder

We just added an instance of UIViewController, but we actually need an instance of SwitchViewController, so let's change our view controller's class to SwitchViewController. Single-click the View Controller icon in the nib's main window, and press

The window representing your view controller in Interface Builder

The identity inspector allows you to specify the class of the currently selected object. Our view controller is currently specified as a UIViewController, and it has no actions defined. Click inside the combo box labeled Class, the one at the top of the inspector that currently reads UIViewController. Change the Class to SwitchViewController. Once you make that change, the switchViews: action method should appear in the section labeled Class Actions (see Figure 6-15). You should also notice that in the nib's main window, the name of that new icon has switched from View Controller to Switch View Controller.

The identity inspector

Figure 6.14. The identity inspector

The identity inspector after changing the class to SwitchViewController

Figure 6.15. The identity inspector after changing the class to SwitchViewController

We now need to build our root controller's view. The root controller's content view will consist of a toolbar that occupies the bottom of the screen.

Remember that new window that appeared when we dragged the generic view controller onto the main nib window (see Figure 6-13)? We'll build the view for our root controller, SwitchViewController, in that window.

As a reminder, SwitchViewController's job is to switch between the blue view and the yellow view. To do that, it will need a way for the user to change the views, and for that, we're going to use a toolbar with a button. Let's build the toolbar view now.

Drag a View from the library onto the window shown in Figure 6-13. Hint: it's the one with a gray background that says View. The gray background should be replaced by this new view.

Now grab a toolbar from the library, drag it onto your view, and place it at the bottom, so that it looks like Figure 6-16.

The toolbar features a single button. Let's use that button to let the user switch between the different content views. Double-click the button, and change its title to Switch Views. Press the return key to commit your change.

Now, we can link the toolbar button to our action method. Before we do that, though, we should warn you: toolbar buttons aren't like other iPhone controls. They support only a single target action, and they trigger that action only at one well-defined moment, the equivalent of a Touch Up Inside event on other iPhone controls.

Adding a toolbar to the view controller's view

Figure 6.16. Adding a toolbar to the view controller's view

Instead of using the connections inspector to connect this button to our action, single-click the Switch Views button, wait a second or two to avoid a double-click, and then single-click the button again to select it. You can confirm you have the button selected by looking at the title bar of the attributes inspector (

Adding a toolbar to the view controller's view

Once you have the Switch Views button selected, control-drag from it over to the Switch View Controller icon, and select the switchViews: action. If the switchViews: action doesn't pop up and instead you see an outlet called delegate, you've most likely control-dragged from the toolbar rather than the button. To fix it, just make sure you've got the button and not the toolbar selected and redo your control-drag.

Earlier, we created an outlet in View_SwitcherAppDelegate.h so our application could get to our instance of SwitchViewController and add its view to the main application window. Now, we need to connect the instance of SwitchViewController in our nib to that outlet. Control-drag from the View_Switcher App Delegate icon to the Switch View Controller icon, and select the switchViewController outlet. You may see a second outlet with a similar name called viewController. If you do, make sure you connect to switchViewController and not viewController.

That's all we need to do here, so save your nib file, and head back to Xcode so that we can implement SwitchViewController.

Writing SwitchViewController.m

It's time to write our root view controller. Its job is to switch between the yellow view and the blue view whenever the user clicks the Switch Views button.

Making the following changes to SwitchViewController.m. You can feel free to delete the commented-out methods provided by the template if you want.

#IMPORT "SwitchViewController.h"
#import "BlueViewController.h"
#import "YellowViewController.h"

@implementation SwitchViewController
@synthesize yellowViewController;
@synthesize blueViewController;

- (void)viewDidLoad
{
    BlueViewController *blueController = [[BlueViewController alloc]
              initWithNibName:@"BlueView" bundle:nil];
    self.blueViewController = blueController;
    [self.view insertSubview:blueController.view atIndex:0];
    [blueController release];
    [super viewDidLoad];
}
- (IBAction)switchViews:(id)sender
{
    if (self.yellowViewController.view.superview == nil)
    {
        if (self.yellowViewController == nil)
        {
            YellowViewController *yellowController =
            [[YellowViewController alloc] initWithNibName:@"YellowView"
                                                   bundle:nil];
            self.yellowViewController = yellowController;
            [yellowController release];
        }
        [blueViewController.view removeFromSuperview];
        [self.view insertSubview:yellowViewController.view atIndex:0];
    }
else
    {
        if (self.blueViewController == nil)
        {
            BlueViewController *blueController =
            [[BlueViewController alloc] initWithNibName:@"BlueView"
                                                 bundle:nil];
            self.blueViewController = blueController;
            [blueController release];
        }
        [yellowViewController.view removeFromSuperview];
        [self.view insertSubview:blueViewController.view atIndex:0];
    }
}
...

Also, add the following code to the existing didReceiveMemoryWarning method:

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview
    [super didReceiveMemoryWarning];

    // Release anything that's not essential, such as cached data
    if (self.blueViewController.view.superview == nil)
        self.blueViewController = nil;
    else
        self.yellowViewController = nil;
}

and add the following two statements to the dealloc method:

- (void)dealloc {
    [yellowViewController release];
    [blueViewController release];
    [super dealloc];
}
@end

The first method we added, viewDidLoad, overrides a UIViewController method that gets called when the nib is loaded. How could we tell? Option–double-click the method name, and take a look at the document that appears. The method is defined in our superclass and is intended to be overridden by classes that need to get notified when the view has finished loading.

We override viewDidLoad to create an instance of BlueViewController. We use the initWithNibName method to load the BlueViewController instance from the nib file BlueView.xib. Note that the filename provided to initWithNibName does not include the .xib extension. Once the BlueViewController is created, we assign this new instance to our blueViewController property.

BlueViewController *blueController = [[BlueViewController alloc]
        initWithNibName:@"BlueView" bundle:nil];
self.blueViewController = blueController;

Next, we insert the blue view as a subview of the root view. We insert it at index zero, which tells iPhone to put this view behind everything else. Sending the view to the back ensures that the toolbar we created in Interface Builder a moment ago will always be visible on the screen, since we're inserting the content views behind it.

[self.view insertSubview:blueController.view atIndex:0];

Now, why didn't we load the yellow view here also? We're going to need to load it at some point, so why not do it now? Good question. The answer is that the user may never tap the Switch Views button. The user might come in, use the view that's visible when the application launches, and then quit. In that case, why use resources to load the yellow view and its controller?

Instead, we'll load the yellow view the first time we actually need it. This is called lazy loading, and it's a standard way of keeping memory overhead down. The actual loading of the yellow view happens in the switchViews: method, so let's take a look at that.

switchViews: first checks which view is being swapped in by checking to see whether yellowViewController's view's superview is nil. This will return YES if one of two things are true. First, if yellowViewController exists but its view is not being shown to the user, that view will have no superview because it's not presently in the view hierarchy and the equation will evaluate to YES. Second, if yellowViewController doesn't exist because it hasn't been created yet or was flushed from memory, it will also return YES.

if (self.yellowViewController.view.superview == nil)
{

We then check to see whether yellowViewController is nil. If it is, that means there is no instance of yellowViewController, and we need to create one. This could happen because it's the first time the button has been pressed or because the system ran low on memory and it was flushed. In this case, we need to create an instance of YellowViewController as we did for the BlueViewController in the viewDidLoad method:

if (self.yellowViewController == nil)
{
    YellowViewController *yellowController =
    [[YellowViewController alloc] initWithNibName:@"YellowView"
                                           bundle:nil];
self.yellowViewController = yellowController;
    [yellowController release];
}

At this point, we know that we have a yellowViewController instance, because either we already had one or we just created it. Then, we remove blueViewController's view from the view hierarchy and add yellowViewController's:

[blueViewController.view removeFromSuperview];
[self.view insertSubview:yellowViewController.view atIndex:0];
}

If self.yellowViewController.view.superview is not nil, then we have to do the same thing, but for blueViewController. Although we create an instance of blueViewController in viewDidLoad, it is still possible that the instance has been flushed because memory got low. Now, in this application, the chances of memory running out are slim, but we're still going to be good memory citizens and make sure we have an instance before proceeding:

else
{
   if (self.blueViewController == nil)
   {
       BlueViewController *blueController =
       [[BlueViewController alloc] initWithNibName:@"BlueView"
                                            bundle:nil];
       self.blueViewController = blueController;
       [blueController release];
   }
   [yellowViewController.view removeFromSuperview];
   [self.view insertSubview:blueViewController.view atIndex:0];
 }

In addition to not using resources for the yellow view and controller if the Switch Views button is never tapped, lazy loading also gives us the ability to release whichever view is not being shown to free up its memory. iPhone OS will call the UIViewController method didReceiveMemoryWarning, which is inherited by every view controller, when memory drops below a system-determined level.

Since we know that either view will get reloaded the next time it gets shown to the user, we can safely release either controller, something we do by adding a few lines to the existing didReceiveMemoryWarning method:

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it
                                     // doesn't have a superview
// Release anything that's not essential, such as cached data
    if (self.blueViewController.view.superview == nil)
        self.blueViewController = nil;
    else
        self.yellowViewController = nil;
}

This newly added code checks to see which view is currently being shown to the user and releases the controller for the other view by assigning nil to its property. This will cause the controller, along with the view it controls, to be deallocated, freeing up its memory. Lazy loading is a key component of resource management on iPhone and should be implemented anywhere you can. In a complex, multiview application, being responsible and flushing unused objects from memory can be the difference between an application that works well and one that crashes periodically because it ran out of memory.

Implementing the Content Views

The two content views that we are creating in this application are extremely simple. They each have one action method that is triggered by a button, and neither one needs any outlets. The two views are also nearly identical. In fact, they are so similar that they could have been represented by the same class. We chose to make them two separate classes, because that's how most multiview applications are constructed. Let's declare an action method in each of the header files. First, in BlueViewController.h, add the following declaration:

#import <UIKit/UIKit.h>
@interface BlueViewController : UIViewController {

}
-(IBAction)blueButtonPressed;
@end

Save it, and then add the following line to YellowViewController.h:

#import <UIKit/UIKit.h>

@interface YellowViewController : UIViewController {

}
- (IBAction)yellowButtonPressed;
@end

Save this one as well, and then double-click BlueView.xib to open it in Interface Builder so we can make a few changes. First, we have to tell it that the class that will load this nib from disk is BlueViewController, so single-click the File's Owner icon and press

Implementing the Content Views

Single-click the icon called View and then press

Implementing the Content Views
The Simulated User Interface Elements section of the View's attributes inspector

Figure 6.17. The Simulated User Interface Elements section of the View's attributes inspector

Next, we'll change the size of the view in the nib. In the attribute inspector, the top section is labeled Simulated User Interface Elements. If we set these drop-downs to reflect which top and bottom elements are used in our application, Interface Builder will automatically calculate the size of the remaining space. The status bar is already specified. If you select the Bottom Bar pop-up, you can select Toolbar to indicate that the enclosing view has a toolbar. By setting this, Interface Builder will automatically calculate the correct size for our view so that you know how much space you have to work with. You can press

The Simulated User Interface Elements section of the View's attributes inspector

Drag a Round Rect Button from the library over to the window. Double-click the button, and change its title to Press Me. You can place the button anywhere that looks good to you. Next, switch to the connections inspector (by pressing

The Simulated User Interface Elements section of the View's attributes inspector

We have one more thing to do in this nib, which is to connect the BlueViewController's view outlet to the view in the nib. The view outlet is inherited from the parent class, UIViewController, and gives the controller access to the view it controls. When we changed the underlying class of the file's owner, the existing outlet connections were broken. As a result, we need to reestablish the connection from the controller to its view. Control-drag from the File's Owner icon to the View icon, and select the view outlet to do that.

Save the nib, go back to Xcode, and double-click YellowView.xib. We're going to make almost the same exact changes to this nib file. We need to change the file's owner from NSObject to YellowViewController using the identity inspector, change the view's height to 416 pixels using the size inspector, and change the view's background to a nice yellow color using the attributes inspector. You'll also need to add a round rectangular button to this view, give it a label of Press Me, Too, and connect that button's Touch Up Inside event to the yellowButtonPressed action method in File's Owner. Finally, control-drag from the File's Owner icon to the View icon, and connect to the view outlet.

Once all that is done, save the nib, and go back to Xcode.

The two action methods we're going to implement do nothing more than show an alert, something you already know how to do, so go ahead and add the following code to BlueViewController.m:

#import "BlueViewController.h"

@implementation BlueViewController

- (IBAction)blueButtonPressed
{
    UIAlertView *alert = [[UIAlertView alloc]
         initWithTitle:@"Blue View Button Pressed"
               message:@"You pressed the button on the blue view"
               delegate:nil
    cancelButtonTitle:@"Yep, I did."
    otherButtonTitles:nil];
    [alert show];
    [alert release];
}
...

Save, switch over to YellowViewController.m, and add this very similar code to that file:

#import "YellowViewController.h"

@implementation YellowViewController

-(IBAction)yellowButtonPressed
{
    UIAlertView *alert = [[UIAlertView alloc]
        initWithTitle:@"Yellow View Button Pressed"
              message:@"You pressed the button on the yellow view"
             delegate:nil
    cancelButtonTitle:@"Yep, I did."
    otherButtonTitles:nil];
    [alert show];
    [alert release];
}
...

Save it, and we're ready to try it. When our application launches, it'll show the view we built in BlueView.xib, and when you tap the Switch Views button, it will change to show us the view that we built in YellowView.xib. Tap it again, and it goes back to the view we built in BlueView.xib. Whether you tap the button on the blue or yellow view, you'll get an alert view with a message indicating which button was pressed. This alert shows us that the correct controller class is getting called for the view that is being shown.

The transition between the two views is kind of abrupt, though. Gosh, if only there were some way to make the transition look nicer.

Animating the Transition

Of course, there is a way to make the transition look nicer! We can animate the transition in order to give the user visual feedback of the change. UIView has several class methods we can call to indicate that the transition should be animated, to indicate the type of transition that should be used, and to specify how long the transition should take.

Go back to SwitchViewController.m, and replace your switchViews: method with this new version:

- (IBAction)switchViews:(id)sender
{
    [UIView beginAnimations:@"View Flip" context:nil];
    [UIView setAnimationDuration:1.25];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

    if (self.yellowViewController.view.superview == nil)
    {
        if (self.yellowViewController == nil)
        {
            YellowViewController *yellowController =
            [[YellowViewController alloc] initWithNibName:@"YellowView"
                                                   bundle:nil];
            self.yellowViewController = yellowController;
            [yellowController release];
        }
        [UIView setAnimationTransition:
         UIViewAnimationTransitionFlipFromRight
                               forView:self.view cache:YES];

        [blueViewController viewWillAppear:YES];
        [yellowViewController viewWillDisappear:YES];

        [blueViewController.view removeFromSuperview];
        [self.view insertSubview:yellowViewController.view atIndex:0];
        [yellowViewController viewDidDisappear:YES];
        [blueViewController viewDidAppear:YES];
}
else
{
    if (self.blueViewController == nil)
    {
        BlueViewController *blueController =
        [[BlueViewController alloc] initWithNibName:@"BlueView"
                                             bundle:nil];
        self.blueViewController = blueController;
        [blueController release];
    }
    [UIView setAnimationTransition:
     UIViewAnimationTransitionFlipFromLeft
                           forView:self.view cache:YES];
     [yellowViewController viewWillAppear:YES];
     [blueViewController viewWillDisappear:YES];

     [yellowViewController.view removeFromSuperview];
     [self.view insertSubview:blueViewController.view atIndex:0];
     [blueViewController viewDidDisappear:YES];
     [yellowViewController viewDidAppear:YES];
 }
 [UIView commitAnimations];
}

Compile this new version, and run your application. When you tap the Switch Views button, instead of the new view just appearing, the view will flip over, as shown in Figure 6-18.

In order to tell iPhone that we want a change animated, we need to declare an animation block and specify how long the animation should take. Animation blocks are declared by using the UIView class method beginAnimations:context:, like so:

[UIView beginAnimations:@"View Flip" context:nil];
[UIView setAnimationDuration:1.25];

beginAnimations:context: takes two parameters. The first is an animation block title. This title comes into play only if you take more direct advantage of Core Animation, the framework behind this animation. For our purposes, we could have used nil. The second parameter is a (void *) that allows you to specify an object whose pointer you'd like associated with this animation block. We used nil here, since we don't have any need to do that.

The view transition animated using the flip style

Figure 6.18. The view transition animated using the flip style

After that, we set the animation curve, which determines the timing of the animation. The default, which is a linear curve, causes the animation to happen at a constant speed. The option we set here indicates that it should change the speed so that it is slow at the beginning and end of the transition but faster in the middle. This gives the animation a more natural, less mechanical appearance.

[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

Next, we have to specify the transition to use. At the time of this writing, four view transitions are available on the iPhone:

  • UIViewAnimationTransitionFlipFromLeft

  • UIViewAnimationTransitionFlipFromRight

  • UIViewAnimationTransitionCurlUp

  • UIViewAnimationTransitionCurlDown

We chose to use two different effects, depending on which view was being swapped in. Using a left flip for one transition and a right flip for the other will make the view seem to flip back and forth. The cache option speeds up drawing by taking a snapshot of the view when the animation begins and using that image rather than redrawing the view at each step of the animation. You should always have it cache the animation unless the appearance of the view may need to change during the animation.

[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight
               forView:self.view cache:YES];

After we set the transition, we make two calls, one on each of the views being used in the transition:

[self.blueViewController viewWillAppear:YES];
[self.yellowViewController viewWillDisappear:YES];

When we're all done swapping the views, we make two more calls on those views:

[self.yellowViewController viewDidDisappear:YES];
[self.blueViewController viewDidAppear:YES];

The default implementations of these methods in UIViewController do nothing, so our calls to viewDidDisappear: and viewDidAppear: don't do anything, since our controllers didn't override those methods. It's important to make these calls even if you know you're not using them.

Why is it important to make these calls even though they do nothing? Even though we're not using those methods now, we might choose to in the future. It's also possible that UIViewController's implementation to those methods won't always be empty, so failing to call these methods could cause our application to behave oddly after a future update of the operating system. The performance hit for making these four calls is meaningless, since they trigger no code, and by putting them in, we can be sure that our application will continue to work.

When we're all done specifying the changes to be animated, we call commitAnimations on UIView. Everything between the start of the animation block and the call to commitAnimations will be animated together.

Thanks to Cocoa Touch's use of Core Animation under the hood, we're able to do fairly sophisticated animation with only a handful of code.

Switching Off

Whoo-boy! Creating our own multiview controller was a lot of work, wasn't it? You should have a very good grasp on how multiview applications are put together now that you've built one from scratch. Although Xcode contains project templates for the most common types of multiview applications, you need to understand the overall structure of these types of applications so you can build them yourself from the ground up. The delivered templates are incredible timesavers, but at times, they simply won't meet your needs.

In the next three chapters, we're going to continue building multiview applications to reinforce the concepts from this chapter and to give you a feel for how more complex applications are put together. In the next chapter, we'll construct a tab bar application, and in the two chapters after that, we'll learn how to construct a navigation-based application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.94.193