Multiview Applications - Beginning iPhone Development: Exploring the iOS SDK, Seventh Edition (2014)

Beginning iPhone Development: Exploring the iOS SDK, Seventh Edition (2014)

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 iOS 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 the app may appear on the screen.

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, establishing a strong foundation for taking advantage of the various multiview controllers that Apple provides.

But before we start building our application, let’s see how multiple-view applications can be useful.

Common Types of Multiview Apps

Strictly speaking, we have worked with multiple views in our previous applications, since buttons, labels, and other controls are all subclasses of UIView and they can all go into the view hierarchy. But when Apple uses the term view in documentation, it is generally referring to a UIViewor one of its subclasses that has 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 your 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 button in the lower-right corner, the view transitions to a configuration view that lets you configure the list of stocks tracked by the application.

image

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, including 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, called 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.

image

Figure 6-2. The Phone application is an example of a multiview application using a tab bar

Another common kind of multiview iPhone application is the navigation-based application, which features a navigation controller that uses a navigation bar to control a hierarchical series of views. The Settings application is a good example. In Settings, the first view you get is a series of rows, each row corresponding to a cluster of settings or a specific app. Touching one of those rows takes you to a new view where you can customize one particular set of settings. Some views present a list that allows you to dive even deeper. The navigation controller keeps track of how deep you go and gives you a control to let you make your way back to the previous view.

For example, if you select the Sounds preference, you’ll be presented a view with a list of sound-related options. At the top of that view is a navigation bar with a left arrow labeled Settings that takes you back to the previous view if you tap it. Within the sound options is a row labeledRingtone. Tap Ringtone, and you’re taken to a new view featuring a list of ringtones and a navigation bar that takes you back to the main Sounds preference view (see Figure 6-3). A navigation-based application is useful when you want to present a hierarchy of views.

image

Figure 6-3. The iPhone Settings application is an example of a multiview application using a navigation bar

On the iPad, most navigation-based applications, such as Mail, are implemented using a split view, where the navigation elements appear on the left side of the screen, and the item you select to view or edit appears on the right. You’ll learn more about split views in Chapter 11.

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 Music 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.

image

Figure 6-4. The Music application uses both a navigation bar and a tab bar

Some applications use a toolbar, which is often confused with a tab bar. A tab bar is used for selecting one and only one option from among two or more options. A toolbar can hold buttons and certain other controls, but those items are not mutually exclusive. A perfect example of a toolbar is at the bottom of the main Safari view (see Figure 6-5). If you compare the toolbar at the bottom of the Safari view with the tab bar at the bottom of the Phone or Music application, you’ll find the two pretty easy to tell apart. The tab bar has multiple segments, exactly one of which (the selected one) is highlighted with a tint color; but on a toolbar, normally every enabled button is highlighted.

image

Figure 6-5. Mobile Safari features a toolbar at the bottom. The toolbar is like a free-form bar that allows you to include a variety of controls

Each of these multiview application types uses a specific controller class from the UIKit. Tab bar interfaces are implemented using the class UITabBarController and navigation interfaces are implemented using UINavigationController. We’ll describe their use in detail in the next few chapters.

The Architecture of a Multiview Application

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

When first launched, View Switcher will look like Figure 6-6, 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.

image

Figure 6-6. When you first launch the View Switcher application, you’ll see a blue view with a button and a toolbar with its own button

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

image

Figure 6-7. When you press the Switch Views button, the blue view flips over to reveal the yellow view

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-8).

image

Figure 6-8. When the Press Me or Press Me, Too button is pressed, an alert is displayed

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.

Before we start building our application, let’s talk about the way iPhone multiview applications are put together. Most multiview applications use the same basic pattern.

The Root Controller

The storyboard is a key player here since it will contain all the views and view controllers for our application. We’re going to create a storyboard with 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 (as in “the root of the tree” or “the root of all evil”) 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, although 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, it is the view that specifies whether it is OK to automatically rotate to a new orientation. However, the root controller can pass responsibility for tasks 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 view 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 is built. Taken together, each of these pairings is called a scene within a storyboard. Each scene consists of a view controller and a content view, which may be an instance of UIView or one of its subclasses. Unless you are doing something really unusual, your content view will always have an associated view controller and will sometimes subclass UIView. Although you can create your interface in code rather than using Interface Builder, few people choose that route because it is more time-consuming and the code is difficult to maintain.

In this project, we’ll be creating a new controller class for each content view. 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 (the button is in the toolbar) is pressed, the root controller swaps out the blue view controller and swaps in a yellow view controller, instantiating that controller if it needs to do so. Confused? If so, don’t worry because this will become clearer as we walk through the code.

Building View Switcher

Enough theory! Let’s go ahead and build our project. Select File image New image Project… or press imageimageN. When the template selection sheet opens, select Single View Application and then click Next. On the next page of the assistant, enter View Switcher as the Product Name, set theLanguage to Objective-C and the Devices pop-up button to Universal. Also make sure the check box labeled Use Core Data is unchecked. When everything is set up correctly, click Next to continue. On the next screen, navigate to wherever you’re saving your projects on disk and click theCreate button to create a new project directory.

Renaming the View Controller

As you’ve already seen, the Single View Application template supplies an application delegate, a view controller, and a storyboard. The view controller class is called ViewController. In this application, we are going to be dealing with three view controllers, but most of the logic will be in the main view controller. Its task will be to switch the display so that the view from one of the other view controllers is showing at all times. To make the role of the main view controller clear, we’d like to give it a better name, such as SwitchingViewController. There are several places in the project where the view controller’s class name is referenced. To change its name, we need to update all of those places. Fortunately, Xcode has a nifty feature that will do that for us. In the Project Navigator, select ViewController.h, and then double-click the class name after@interface in the editor area to select it and right-click it. In the menu that appears, select Refactor and then Rename… (see Figure 6-9).

image

Figure 6-9. Using the Refactor image Rename menu item to change the name of the main view controller

In the dialog that appears, make sure that Rename related files is checked and change the view controller name to SwitchingViewController, as shown in Figure 6-10.

image

Figure 6-10. Renaming the view controller

Press Preview and Xcode opens a new window showing all of the places where it needs to change the view controller’s name (see Figure 6-11).

image

Figure 6-11. Previewing the changes that Xcode will make to change the name of the view controller

Press Save to continue with the rename operation. Xcode will prompt you to enable automatic snapshots. Doing so is a good idea, because if you decide later that you don’t want to go through with the change, you can easily revert it. Press Enable and Xcode will complete the rename. When it’s done, you should see that the name of the view controller has changed in the Project Navigator and the content of the file in the editor area has also changed, as shown in Figure 6-12.

image

Figure 6-12. After the rename, Xcode shows the new view controller name

Tip You can create a snapshot at any time by selecting Create Snapshot… from Xcode’s File menu. Once you have a snapshot, you can revert your workspace by using File image Restore Snapshot…. Xcode will show a list of the snapshots from which you can choose the one to be used for the restore.

Adding the Content View Controllers

We’ll need two additional view controllers to display the content views. In the Project Navigator, right-click the View Switcher group and select New File…. In the template dialog, choose Cocoa Touch Class from the iOS Source section and press Next. Name the new classBlueViewController, make it a subclass of UIViewController, and make sure that the Also create XIB file check box is not checked, since we are going to add this controller to the storyboard a little later. Press Next and then press Create to save the files for the new view controller. Repeat this process to create the second content view controller, giving it the name YellowViewController.

Modifying SwitchingViewController.m

The SwitchingViewController class will need an action method that will toggle between the blue and yellow views. We won’t create any outlets, but we will need two other pointers: one to each of the view controllers that we’ll be swapping in and out. These don’t need to be outlets because we’re going to create them in code rather than in the storyboard. Add the following code to the upper part of SwitchingViewController.m:

#import "SwitchingViewController.h"

#import "YellowViewController.h"
#import "BlueViewController.h"

@interface SwitchingViewController ()

@property (strong, nonatomic) YellowViewController *yellowViewController;
@property (strong, nonatomic) BlueViewController *blueViewController;

@end

Next, add the following empty action method toward the end of the file, just before the final @end line:

- (IBAction)switchViews:(id)sender {

}

@end

In the past, we’ve added action methods directly within Interface Builder, but here you’ll see that we can work the other way around just as well, since IB can see what outlets and actions are already defined in our source code. Now that we’ve declared the action we need, we can set up the minimal user interface for this controller in our storyboard.

Building a View with a Toolbar

We now need to set up the view for SwitchingViewController. As a reminder, this view controller will be our root view controller—the controller that is in play when our application is launched. SwitchingViewController’s content view will consist of a toolbar that occupies the bottom of the screen. Its job is to switch between the blue view and the yellow view, so it will need a way for the user to change the views. For that, we’re going to use a toolbar with a button. Let’s build the toolbar view now.

In the Project Navigator, select Main.storyboard. In the IB editor view, you’ll see our switching view controller. As you can see in Figure 6-13, it’s currently empty and quite dull. This is where we’ll start building our GUI.

image

Figure 6-13. The empty view in the storyboard, just waiting to be filled with interesting stuff

Now, let’s add a toolbar to the bottom of the view. Grab a Toolbar from the library, drag it onto your view, and place it at the bottom so that it looks like Figure 6-14.

image

Figure 6-14. We dragged a toolbar onto our view. Notice that the toolbar features a single button, labeled Item

We want to keep this toolbar stretched across the bottom of the content view no matter what size the view has. To do that, we need to add three layout constraints—one that pins the toolbar to the bottom of the view and another two that pin it to the view’s left and right sides. To do this, select the toolbar in the Document Outline, click the Pin button on the toolbar beneath the storyboard, and change the values in the pop-up, as shown in Figure 6-15.

image

Figure 6-15. Pinning the toolbar to the bottom of the content view

Start by unchecking the Constrain to margins check box, because we want to position the toolbar relative to the edges of the content view, not the blue guidelines that appear near its edges. Next, set the distances to the nearest left, right, and bottom neighbors to zero (if you have correctly positioned the toolbar, they should already be zero). In this case, the nearest neighbor of the toolbar is the content view. You can see this by clicking the small arrow in one of the distance boxes: it opens a pop-up that shows the nearest neighbor and any other neighbors relative to which you could place the toolbar—in this case, there are none. To indicate that these distance constraints should be active, click the three dashed red lines that link the distance boxes to the small square in the center, so that they become solid lines. Finally, change Update Frames to Items of New Constraints (so that the toolbar’s representation in the storyboard moves to its new constrained location) and click Add 3 Constraints.

Now, to make sure you’re on the right track, click the Run button to make this app launch in the iOS simulator. You should see a plain white app start up, with a pale gray toolbar at the bottom containing a lone button. If not, go back and retrace your steps to see what you missed. Rotate the simulator and verify that the toolbar stays fixed at the bottom of the view and stretched right across the screen. If this doesn’t happen, you need to fix the constraints that you just applied to the toolbar.

Linking the Toolbar Button to the View Controller

The toolbar has a single button. We’ll use that button to let the user switch between the different content views. Double-click the button in the storyboard 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 in SwitchingViewController. Before doing that, though, you should be aware that toolbar buttons aren’t like other iOS 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 iOS controls.

Selecting a toolbar button in Interface Builder can be tricky. The easiest way to do it is to expand the Switching View Controller icon in the Document Outline until you can see the button, which is now labeled Switch Views, and then click it. Once you have the Switch Views button selected, Control-drag from it over to the yellow Switching View Controller icon at the top of the scene, as shown in Figure 6-16. Release the mouse and select the switchViews: action from the pop-up. If the switchViews: action doesn’t appear, 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 have the button rather than the toolbar selected, and then redo your Control-drag.

image

Figure 6-16. Linking the toolbar button to the switchViews: method in the view controller class

We have one more thing to point out in this scene, which is SwitchingViewController’s view outlet. This outlet is already connected to the view in the scene. The view outlet is inherited from the parent class, UIViewController, and gives the controller access to the view it controls. When we created the project, Xcode created both the controller and its view, and hooked them up for us. Nice.

That’s all we need to do here, so save your work. Next, let’s get started implementing SwitchingViewController.

Writing the Root View Controller

It’s time to write our root view controller. Its job is to switch between the blue view and the yellow view whenever the user clicks the Switch Views button. In the Project Navigator, select SwitchingViewController.m and modify the viewDidLoad method to set some things up by adding the lines shown here in bold:

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.blueViewController = [self.storyboard
instantiateViewControllerWithIdentifier:
@"Blue"];

self.blueViewController.view.frame = self.view.frame;
[self switchViewFromViewController:nil
toViewController:self.blueViewController];

}

Our implementation of viewDidLoad overrides a UIViewController method that is called when the storyboard is loaded. How could we tell? Hold down the image key (the Option key) and single-click the method named viewDidLoad. A documentation pop-up window will appear (see Figure 6-17). Alternatively, you can select View image Utilities image Show Quick Help Inspector to view similar information in the Quick Help panel. viewDidLoad is defined in our superclass, UIViewController, and is intended to be overridden by classes that need to be notified when the view has finished loading.

image

Figure 6-17. This documentation window appears when you option-click the viewDidLoad method name

This version of viewDidLoad creates an instance of BlueViewController. We use the instantiateViewControllerWithIdentifier: method to load the BlueViewController instance from the same storyboard that contains our root view controller. To access a particular view controller from a storyboard, we use a string as an identifier—in this case “Blue” —which we’ll set up when we configure our storyboard a little more. Once the BlueViewController is created, we assign this new instance to our blueViewController property:

self.blueViewController = [self.storyboard
instantiateViewControllerWithIdentifier:
@"Blue"];

Next, we set the frame of the blue view controller’s view to be the same as that of the switch view controller’s content view, and switch to the blue view controller so that its view appears on the screen:

self.blueViewController.view.frame = self.view.frame;
[self switchViewFromViewController:nil
toViewController:self.blueViewController];

Since we need to perform a view controller switch in several places, the code to do this is in the helper method switchFromViewController:toViewController: that we’ll see shortly.

Now, why didn’t we load the yellow view controller 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 just 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. Fill in the stub of this method that you created earlier by adding the cold shown in bold:

- (IBAction)switchViews:(id)sender {
// Create the new view controller, if required.
if (!self.yellowViewController.view.superview) {
if (!self.yellowViewController) {
self.yellowViewController = [self.storyboard
instantiateViewControllerWithIdentifier:@"Yellow"];
}
} else {
if (!self.blueViewController) {
self.blueViewController = [self.storyboard
instantiateViewControllerWithIdentifier:@"Blue"];
}
}

// Switch view controllers.
if (!self.yellowViewController.view.superview) {
self.yellowViewController.view.frame = self.view.frame;
[self switchViewFromViewController:self.blueViewController
toViewController:self.yellowViewController];
} else {
self.blueViewController.view.frame = self.view.frame;
[self switchViewFromViewController:self.yellowViewController
toViewController:self.blueViewController];
}
}

switchViews: first checks which view is being swapped in by seeing whether yellowViewController’s view’s superview is nil. This will be true if one of two things is true:

· If yellowViewController exists but its view is not being shown to the user, that view will not have a superview because it’s not presently in the view hierarchy, and the expression will evaluate to true.

· If yellowViewController doesn’t exist because it hasn’t been created yet or was flushed from memory, it will also return true.

We then check to see whether yellowViewController exists:

if (!self.yellowViewController.view.superview) {

If it’s a nil pointer, 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) {
self.yellowViewController = [self.storyboard
instantiateViewControllerWithIdentifier:@"Yellow"];
}

If we’re switching in the blue controller, we need to perform the same check to see whether it still exists (since it could have been flushed from memory) and create it if it does not. This is just the same code again, referencing the blue controller instead:

} else {
if (!self.blueViewController) {
self.blueViewController = [self.storyboard
instantiateViewControllerWithIdentifier:@"Blue"];
}
}

At this point, we know that we have a view controller instance because either we already had one or we just created it. We then set the view controller’s frame to match that of the switch view controller’s content view and then we use ourswitchFromViewController:toViewController: method to actually perform the switch:

// Switch view controllers.
if (!self.yellowViewController.view.superview) {
self.yellowViewController.view.frame = self.view.frame;
[self switchViewFromViewController:self.blueViewController
toViewController:self.yellowViewController];
} else {
self.blueViewController.view.frame = self.view.frame;
[self switchViewFromViewController:self.yellowViewController
toViewController:self.blueViewController];
}

The first branch of the if statement is taken if we are switching from the blue view controller to the yellow and vice versa for the else branch.

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. iOS will call the UIViewController methoddidReceiveMemoryWarning, which is inherited by every view controller, when memory drops below a system-determined level.

Since we know that either view will be reloaded the next time it is shown to the user, we can safely release either controller, provided it is not currently on display. We can do this by adding a few lines to the existing didReceiveMemoryWarning method:

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];

if (!self.blueViewController.view.superview) {
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.

Tip Lazy loading is a key component of resource management on iOS, and you should implement it 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 runs out of memory.

The final piece of the puzzle is the switchFromViewController:toViewController: method, which is responsible for the view controller switch. Switching view controllers is a two-step process. First, we need to remove the view for the controller that’s currently displayed, and then we need to add the view for the new view controller. But that’s not quite all—we need to take care of some housekeeping as well. Add the implementation of this method as shown:

- (void)switchViewFromViewController:(UIViewController *)fromVC
toViewController:(UIViewController *)toVC {
if (fromVC != nil) {
[fromVC willMoveToParentViewController:nil];
[fromVC.view removeFromSuperview];
[fromVC removeFromParentViewController];
}

if (toVC != nil) {
[self addChildViewController:toVC];
[self.view insertSubview:toVC.view atIndex:0];
[toVC didMoveToParentViewController:self];
}
}

The first block of code removes the outgoing view controller, but let’s look at the second block first, where we add the incoming view controller. Here’s the first line of code in that block:

[self addChildViewController:toVC];

This code makes the incoming view controller a child of the switching view controller. View controllers like SwitchingViewController that manage other view controllers are referred to as container view controllers. The standard classes UITabBarController andUINavigationController are both container view controllers and they have code that does something similar to what the switchFromViewController:toViewController: method is doing. Making the new view controller a child of the SwitchingViewControllerensures that certain events that are delivered to the root view controller are correctly passed to the child controller when required—for example, it makes sure that rotation is handled properly.

Next, the child view controller’s view is added to that of the SwitchingViewController:

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

Note that the view is inserted in the subviews list of SwitchingViewController at index zero, which tells iOS 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. Finally, we notify the incoming view controller that it has been added as the child of another controller:

[toVC didMoveToParentViewController:self];

This is necessary in case the child view controller overrides this method to take some action when it’s become the child of another controller.

Now that you’ve seen how a view controller is added, the code that removes a view controller from its parent is much easier to understand—all we do is reverse each of the steps that we performed when adding it:

if (fromVC != nil) {
[fromVC willMoveToParentViewController:nil];
[fromVC.view removeFromSuperview];
[fromVC removeFromParentViewController];
}

Implementing the Content Views

At this point, the code is complete, but we can’t run the application yet because we don’t have the blue and yellow content controllers in the storyboard. These two controllers 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.

The two action methods we’re going to implement do nothing more than show an alert (as we did in Chapter 4’s Control Fun application), so go ahead and add this code to BlueViewController.m:

#import "BlueViewController.h"

@implementation BlueViewController

- (IBAction)blueButtonPressed {
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:@"Blue View Button Pressed"
message:@"You pressed the button on the blue view"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action =
[UIAlertAction actionWithTitle:@"Yep, I did"
style:UIAlertActionStyleDefault handler:nil];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
}

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

#import "YellowViewController.h"

@implementation YellowViewController

- (IBAction)yellowButtonPressed {
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:@"Yellow View Button Pressed"
message:@"You pressed the button on the yellow view"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action =
[UIAlertAction actionWithTitle:@"Yep, I did"
style:UIAlertActionStyleDefault handler:nil];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
}

Save this file as well.

Next, select Main.storyboard to open it in Interface Builder so that we can make a few changes. First, we need to add a new scene for BlueViewController. Up until now, each storyboard we’ve dealt with contained just a single controller-view pairing, but the storyboard has more tricks up its sleeve, and holding multiple scenes is one of them. From the object library, drag out another View Controller and drop it in the editing area next to the existing one. Now your storyboard has two scenes, each of which can be loaded dynamically and independently while your application is running. In the row of icons at the top of the new scene, single-click the yellow View Controller icon and press imageimage3 to bring up the Identity Inspector. In the Custom Class section, Class defaults to UIViewController; change it to BlueViewController.

We also need to create an identifier for this new view controller so that our code can find it inside the storyboard. Just below the Custom Class section in the Identity Inspector, you’ll see a Storyboard ID field. Click there and type Blue to match what we used in our code.

So now you have two scenes. We showed you earlier how to configure your app to load this storyboard at launch time, but we didn’t mention anything about scenes there. How will the app know which of these two views to show? The answer lies in the big arrow pointing at the first scene, as shown in Figure 6-18. That arrow points out the storyboard’s default scene, which is what the app shows when it starts up. If you want to choose a different default scene, all you have to do is drag the arrow to point at the scene you want.

image

Figure 6-18. We just added a second scene to our storyboard. The big arrow points at the default scene

Single-click the big square view in the new scene you just added, and then press imageimage4 to bring up the Attributes Inspector. In the inspector’s View section, click the color well that’s labeled Background, and use the pop-up color picker to change the background color of this view to a nice shade of blue. Once you are happy with your blue, close the color picker.

Drag a Button from the library over to the view, using the guidelines to center the button in the view, both vertically and horizontally. We want to make sure that the button stays centered no matter what, so make two constraints to that effect. First select Editor image Align image Horizontal Center in Container from the menu. Then click the new button again and select Editor image Align image Vertical Center in Container from the menu.

Double-click the button and change its title to Press Me. Next, with the button still selected, switch to the Connections Inspector (by pressing imageimage6), drag from the Touch Up Inside event to the yellow View Controller icon at the top of the scene, and connect to the blueButtonPressedaction method. You’ll notice that the text of the button is a blue color by default. Since our background is also blue, there’s a pretty big risk that this button’s text will be hard to see! Switch to the Attributes Inspector with imageimage4, and then use the combined color-picker/pop-up button to change the Text Color value to something else. Depending on how dark your background color is, you might want to choose either white or black.

Now it’s time to do pretty much the same set of things for YellowViewController. Grab yet another View Controller from the object library and drag it into the editor area. Don’t worry if things are getting crowded; you can stack those scenes on top of each other, and no one will mind! Click the View Controller icon for the new scene in the Document Outline and use the Identity Inspector to change its class to YellowViewController and its Storyboard ID to Yellow.

Next, select the YellowViewController‘s view and switch to the Attributes Inspector. There, click the Background color well, select a bright yellow, and then close the color picker.

Next, drag out a Button from the library and use the guidelines to center it in the view. Use the menu actions to create constraints aligning its horizontal and vertical center, just like for the last button. Now change its title to Press Me, Too. With the button still selected, use the Connections Inspector to drag from the Touch Up Inside event to the View Controller icon, and connect to the yellowButtonPressed action method.

When you’re finished, save the storyboard and get ready to take the app for a spin. Hit the Run button in Xcode, and your app should start up and present you with a full screen of blue.

When our application launches, it shows the blue view we built. When you tap the Switch Views button, it will change to show the yellow view that we built. Tap it again, and it goes back to the blue view. If you tap the button centered on the blue or yellow view, you’ll get an alert view with a message indicating which button was pressed. This alert shows that the correct controller class is being 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.

Of course, there is a way to make the transition look nicer! We can animate the transition to give the user visual feedback of the change.

Animating the Transition

UIView has several class methods we can call to indicate that the transition between views 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 SwitchingViewController.m and enhance your switchViews: method by adding the lines shown here in bold:

- (IBAction)switchViews:(id)sender {
// Create the new view controller, if required.
if (!self.yellowViewController.view.superview) {
if (!self.yellowViewController) {
self.yellowViewController = [self.storyboard
instantiateViewControllerWithIdentifier:@"Yellow"];
}
} else {
if (!self.blueViewController) {
self.blueViewController = [self.storyboard
instantiateViewControllerWithIdentifier:@"Blue"];
}
}

// Switch view controllers.
[UIView beginAnimations:@"View Flip" context:NULL];
[UIView setAnimationDuration:0.4];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
if (!self.yellowViewController.view.superview) {
[UIView setAnimationTransition:
UIViewAnimationTransitionFlipFromRight
forView:self.view cache:YES];
self.yellowViewController.view.frame = self.view.frame;
[self switchViewFromViewController:self.blueViewController
toViewController:self.yellowViewController];
} else {
[UIView setAnimationTransition:
UIViewAnimationTransitionFlipFromLeft
forView:self.view cache:YES];
self.blueViewController.view.frame = self.view.frame;
[self switchViewFromViewController:self.yellowViewController
toViewController:self.blueViewController];
}
[UIView commitAnimations];
}

Compile this new version and run your application. When you tap the Switch Views button, instead of the new view just snapping into place, the old view will flip over to reveal the new view, as shown in Figure 6-19.

image

Figure 6-19. One view transitioning to another, using the flip style of animation

To tell iOS 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:NULL];
[UIView setAnimationDuration:0.4];

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 (or any other C data type) whose pointer you would like associated with this animation block. We used NULL here, since we don’t need to do that. We also set the duration of the animation, which tells UIView how long (in seconds) the animation should last.

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, UIViewAnimationCurveEaseInOut, specifies that the animation should start slow but speed up in the middle, and then slow down again at the end. This gives the animation a more natural, less mechanical appearance:

[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

Next, we need to specify the transition to use. At the time of this writing, five iOS view transitions are available:

· UIViewAnimationTransitionFlipFromLeft

· UIViewAnimationTransitionFlipFromRight

· UIViewAnimationTransitionCurlUp

· UIViewAnimationTransitionCurlDown

· UIViewAnimationTransitionNone

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 makes the view seem to flip back and forth. The value UIViewAnimationTransitionNone causes an abrupt transition from one view controller to another. Of course, if you wanted that effect, you wouldn’t bother creating an animation block at all.

The cache option speeds up drawing by taking a snapshot of the view when the animation begins, and uses that image rather than redrawing the view at each step of the animation. You should always cache the animation unless the appearance of the view may need to change during the animation:

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

When we’re finished 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 of 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 that you can build them yourself from the ground up. The standard container controllers (UITabBarController, UINavigationController, and UIPageViewController) are incredible time-savers and you should use them when you can, but, at times, they simply won’t meet your needs.

In the next few 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 Chapter 7, we’ll construct a tab bar application. Let’s get going!