Swapping Views on Rotation
Some applications display entirely different UIs depending on the device’s orientation. The iPhone Music application, for example, displays a scrolling list of songs in portrait mode and a “flickable” Cover Flow view of albums when held in landscape. You, too, can create applications that dramatically alter their appearance by simply switching between views when the phone is rotated.
Our last tutorial in this hour is short and sweet and gives you the flexibility to manage your landscape and portrait views all within the comfort of the IB editor. What’s more, you can still use Auto Layout within each of these views to position your interface objects to accommodate different screen sizes (like the 3.5” and 4” iPhone screens).
The previous examples used a single view and rearranged it (either through Auto Layout or code) to fit a different orientation. When the view is too different or complex for this to be feasible, however, you can use two individual views with a single view controller. This is precisely what we do in this application. We start by adding a second view to the traditional single-view application, and then we design both views and make sure we can easily access them through properties in our code.
Once that is complete, we write the code necessary to swap the views when the device rotates. There is a catch, which you’ll learn about in a bit, but nothing that poses too much of a problem to coders as experienced as we are.
Setting Up the Project
Create a new project named Swapper using the Single View Application template. Although this includes a single view already (which we’ll use for the default portrait display), we need to supplement it with a second landscape view.
Planning the Property and Connections
This application does not implement any real UI elements, but we need to access two UIView instances programmatically. One view is for portrait orientation (portraitView) and another for landscape orientation (landscapeView). We will implement a method to handle orientation changes, but it will not be triggered by any actions.
Adding a Degree to Radians Constant
Later in this exercise, we have to call a special Core Graphics method to define how to rotate views. The method requires a value to be passed in radians rather than degrees. In other words, instead of saying we want to rotate the view 90 degrees, we have to tell it we want to rotate 1.57 radians. To help us handle the conversion, we define a constant for the conversion factor. Multiplying degrees by the constant gets us the resulting value in radians.
To define the constant, add the following line after the #import line in ViewController.m:
Enabling Orientation Changes
As with the previous example, we need to ensure that the implementation of supportedInterfaceOrientations is behaving as we expect in our view controller. Unlike the previous implementation, however, this time we allow the device to rotate only between the two landscape modes and upright portrait.
Update ViewController.m to include the implementation in Listing 16.9.
Listing 16.9. Disable the Upside-Down Orientation
Be sure to also go into the project summary and set the allowed orientations to everything but upside-down.
Designing the Interface
When you are swapping views, the sky is the limit for the design. You build them exactly as you would in any other application. The only difference is that if you have multiple views handled by a single view controller, you must define outlets that encompass all the interface elements.
This example demonstrates just how to swap views, so our work will be a piece of cake.
Creating the Views
Open the MainStoryboard.storyboard file and drag a new instance of the UIView object from the Object Library to the document outline, placing it at the same level in the hierarchy as the view controller, as shown in Figure 16.16. Don’t put the UIView inside the existing view.
Figure 16.16. Add a second view to the scene.
Now, open the default view and add a label, such as Portrait View; make sure that it is selected. Use Editor, Align from the menu bar to set constraints so that it is aligned to the horizontal and vertical centers of the view. Now set a background color to differentiate the view. That finishes one view, but we still have another to do. Unfortunately, you can only edit a view that is assigned to a view controller in IB, so we have to be creative.
Drag the view you just created out of the view controller hierarchy in the document outline, placing it at the same level as the view controller. Drag the second view onto the view controller line in the document outline. You can now edit it by adding a unique background color and a label such as Landscape View. You may want to switch the view controller to simulate a landscape mode while making these edits. When the second view is done, rearrange the view hierarchy again, nesting the portrait view inside the view controller and the landscape view outside the view controller.
If you want to make this more interesting, you’re welcome to add other controls and design the view as you see fit. Our finished landscape and portrait views are shown in Figure 16.17.
Figure 16.17. Edit the two views so that you can tell them apart.
Creating and Connecting the Outlets
To finish up our interface work, we need to connect the two views to two outlets. The default view (nested in the view controller) will be connected to portraitView. The second view will be connected to landscapeView. Switch to the assistant editor and make sure that the document outline is visible.
Because we’re dealing with views rather than objects in our interface design, the easiest way to make these connections is to Control-drag from the respective lines in the document outline to the ViewController.h file. In addition, unlike with most of the projects in this book, we need to create outlets with the storage set to Strong; otherwise, ARC will conveniently get rid of the views when they aren’t visible.
Control-drag from the default (nested) view to below the @interface line in ViewController.h. Create a new outlet for the view called portraitView, with the storage set as Strong. Repeat the process for the second view, naming the connection landscapeView as demonstrated in Figure 16.18.
Figure 16.18. Connect the views to corresponding outlets using a storage type of Strong.
Implementing the Application Logic
For the most part, swapping views is actually easier than the reframing logic we implemented in the last project—with one small exception. Even though we designed one of the views to be in landscape view, it doesn’t “know” that it is supposed to be displayed in a landscape orientation.
Understanding the View-Rotation Logic
For a landscape view to be successfully swapped onto the screen, we need to rotate it and define how big it is. The reason for this is that there is no inherent logic built in to a view that says “hey, I’m supposed to be sideways.” As far as it knows, it is intended to be displayed in portrait mode but has UI elements that are pushed off the sides of display.
Each time we change orientation, we go through three steps: swapping the view, rotating the view to the proper orientation through the transform property, and setting the view’s origin and size via the bounds property.
For example, assume we’re rotating to landscape right orientation:
- First, we can grab the current view size (after rotation) by accessing and storing self.view.bounds. This can be used later to make sure that the new view is set to the proper size:
- Second, we swap out the view by assigning self.view, which contains the current view of the view controller, to the landscapeView property. If we left things at that, the view would properly switch, but it wouldn’t be rotated into the landscape orientation. A landscape view displayed in a portrait orientation isn’t a pretty thing. For example:
- Next, to deal with the rotation, we define the transform property of the view. This property determines how the view will be altered before it is displayed. To meet our needs, we have to rotate the view 90 degrees to the right (for landscape right), –90 degrees to the left (for landscape left), and 0 degrees for portrait. As luck would have it, the Core Graphics C function, CGAffineTransformMakeRotation(), accepts a rotation value in radians and provides an appropriate structure to the transform property to handle the rotation. For example:
- The final step is to set the bounds property of the view to the bounds that we stored in step 1. For example:
Now that you understand the steps, let’s take a look at the actual implementation.
Adding the View-Rotation Logic
All the rotation magic happens within a single method: supportedInterfaceOrientations.
Open the ViewController.m file and implement the method, as shown in Listing 16.7.
Listing 16.10. Rotate the View into the Proper Orientation
Line 4 grabs the current bounds of the scene’s view after the rotation has occurred, and stores it in currentBounds.
Lines 6–8 handle rotation to the right (landscape right). Lines 9–11 deal with rotation to the left (landscape left). Finally, lines 13–14 configure the view for the default orientation, portrait.
In the very last step, line 16, the bounds of the view we swapped in are set to the currentBounds that we stored when the method started.
Building the Application
Save the implementation file, and then run and test the application. As you rotate the device or the iOS simulator, your views should be swapped in and out appropriately. This approach gives you a good combination of flexibility while keeping the benefits of Auto Layout. Unfortunately, it also means that you have to manage twice as many objects in your code.
When designing your own applications, you need to strike a balance between interface flexibility and code complexity. In some cases, it’s just easier to design a different scene and use a second view and view controller to handle other orientations.