Home > Articles > Programming > Mac and iOS Programming

This chapter is from the book

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

Implementation Overview

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:

#define kDeg2Rad (3.1415926/180.0)

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

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

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

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

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

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:

  1. 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:
    currentBounds=self.view.bounds;
  2. 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:
    self.view=self.landscapeView;
  3. 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:
    self.view.transform=CGAffineTransformMakeRotation(deg2rad*(90));
  4. The final step is to set the bounds property of the view to the bounds that we stored in step 1. For example:
    self.view.bounds=currentBounds;

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

 1: - (void)didRotateFromInterfaceOrientation:
 2:     (UIInterfaceOrientation)fromInterfaceOrientation {
 3:
 4:     CGRect currentBounds=self.view.bounds;
 5:
 6:     if (self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
 7:         self.view=self.landscapeView;
 8:         self.view.transform=CGAffineTransformMakeRotation(kDeg2Rad*(90));
 9:     } else if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
10:         self.view=self.landscapeView;
11:         self.view.transform=CGAffineTransformMakeRotation(kDeg2Rad*(-90));
12:     } else {
13:         self.view=self.portraitView;
14:         self.view.transform=CGAffineTransformMakeRotation(0);
15:     }
16:     self.view.bounds=currentBounds;
17: }

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.

InformIT Promotional Mailings & Special Offers

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

Overview


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

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

Collection and Use of Information


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

Questions and Inquiries

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

Online Store

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

Surveys

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

Contests and Drawings

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

Newsletters

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

Service Announcements

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

Customer Service

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

Other Collection and Use of Information


Application and System Logs

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

Web Analytics

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

Cookies and Related Technologies

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

Do Not Track

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

Security


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

Children


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

Marketing


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

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

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

Correcting/Updating Personal Information


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

Choice/Opt-out


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

Sale of Personal Information


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

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

Supplemental Privacy Statement for California Residents


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

Sharing and Disclosure


Pearson may disclose personal information, as follows:

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

Links


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

Requests and Contact


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

Changes to this Privacy Notice


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

Last Update: November 17, 2020