Home > Articles > Programming > Mac and iOS Programming

This chapter is from the book

Programmatically Defined Interfaces

In the previous example, you learned how the IB editor can help quickly create interface layouts that look as good horizontally as they do vertically and that can resize between the 3.5” and 4” iPhone displays. Unfortunately, in plenty of situations, IB can’t quite accommodate. Irregularly spaced controls and tightly packed layouts rarely work out the way you expect. You may also find yourself wanting to tweak the interface to look completely different—positioning objects that were at the top of the view down by the bottom and so on.

In cases like this, consider implementing the UI (or portions of it) completely in code. But, what about the nice and neat drag-and-drop approach? Well, using code isn’t as convenient as drawing your interface in IB, but it isn’t difficult. We’re going to move to a project that is the exact opposite of our last few examples—rather than building a responsive interface without code, we’re going to only use code to create an interface.

Implementation Overview

In this tutorial, we create a very simple application with three UI elements: two buttons (Button A and Button B) and a label. The buttons trigger a method to set the label to the title of the button. Most important, however, is that the interface reacts properly to orientation and size changes.

In the portrait orientation, the buttons are drawn with the label sandwiched between them. In landscape, the buttons move closer to the bottom, and the label repositions above them. The final output will resemble Figure 16.15.

Figure 16.15

Figure 16.15. Buttons resize and reposition appropriately (all handled in code).

Take note that the positioning of the buttons and the label cannot be handled in Auto Layout (at least not through any straightforward approach). When you encounter issues that can’t be solved in Auto Layout, there’s no harm in coding your way out of the forest.

To handle the rotation and resizing of the objects, we use the bounds property of the scene’s view. This gives us the width and height of the device corresponding to whatever orientation it is in. We then use these values to position the UI elements on the screen. By basing the positioning on the bounds, the size of the device screen and orientation are largely irrelevant, as you’ll soon see.

Setting Up the Project

Unlike the previous example, we can’t rely pointing and clicking for the interface, so there is a bit of code in the project. Once again, create a new single-view iOS application project and name it AllInCode.

Planning the Properties and Connections

In this exercise, you manually resize and reposition three UI elements: two buttons (UIButton) and one label (UILabel). Although we aren’t creating these with outlets, we define properties for them: buttonA, buttonB, and theLabel should suffice.

We also implement a method: handleButton, which updates the onscreen label to show the title of a button that was tapped. Like the properties, this won’t be declared using IB, but we’ll be using it just like an IBAction. We also add two additional methods, initInterface and updateInterface, to handle setting up and updating the interface, respectively. These will be triggered by a change in orientation, so our next step is to set up the project to properly handle orientation changes.

Enabling Orientation Changes

For this project, enable support of all orientations. To do this, start by updating the project summary (click the blue project icon at the top of the project navigator) and select all the device orientations within the Supported Interface Orientations section. Next, add the supportedInterfaceOrientations method to ViewController.m and have it return the constant UIInterfaceOrientationMaskAll, as shown in Listing 16.2.

Listing 16.2. Support All Interface Orientations

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

Programming the Interface

We’ve now reached the point in the project where normally I’d say, “Let’s design the interface.” This time, however, there isn’t going to be a visual design, just code. In fact, you’ve already seen the two screenshots that accompany this project, so if you’re just skimming pictures, you’d better flip through a few more pages.

Defining Properties and Methods

We start by defining the properties and methods that the view controller will be using. Recall that we’re adding three properties: buttonA, buttonB, and theLabel. We’ also have three methods that we should prototype in ViewController.h: initInterface, updateInterface, and handleButton.

Edit ViewController.h, adding the properties and method prototypes, as shown in Listing 16.3.

Listing 16.3. Add the Properties and Method Prototypes to ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak,nonatomic) UIButton *buttonA;
@property (weak,nonatomic) UIButton *buttonB;
@property (strong,nonatomic) UILabel *theLabel;

- (void)initInterface;
- (void)updateInterface;
- (void)handleButton:(id)sender;

@end

Look closely and you’ll notice that theLabel is set to use a strong property reference. Unfortunately, this is a result of overzealous memory cleanup by ARC. If we use weak instead, the label will actually be removed from memory before we can even get it onto the screen. Using strong ensures that the label sticks around as long as the ViewController object is active.

Everything else should look pretty straightforward. The initInterface and updateInterface methods don’t take any arguments or return any values. The handleButton method is styled after a typical IBAction because it will behave exactly like a typical action; it’s just being defined by hand rather than being built for us.

Initializing the Interface Properties

The next step is to add the initInterface method to ViewController.m. The purpose of this method is to configure all the interface elements (the two buttons and the label) so that they’re ready to be added to the interface, but not display them just yet.

By keeping the display logic separated from the initialization logic, we can build a method that can be called at any time to update the interface. This method, aptly named updateInterface, is called at the end of the initInterface and anytime interface rotation is sensed.

Add the initInterface method from Listing 16.4 to ViewController.m.

Listing 16.4. Prepare the Interface But Don’t Display It Yet

 1: - (void)initInterface {
 2:     self.buttonA =[UIButton buttonWithType:UIButtonTypeRoundedRect];
 3:     [self.buttonA addTarget:self action:@selector(handleButton:)
 4:            forControlEvents:UIControlEventTouchUpInside];
 5:     [self.buttonA setTitle:@"Button A" forState:UIControlStateNormal];
 6:
 7:     self.buttonB =[UIButton buttonWithType:UIButtonTypeRoundedRect];
 8:     [self.buttonB addTarget:self action:@selector(handleButton:)
 9:           forControlEvents:UIControlEventTouchUpInside];
10:     [self.buttonB setTitle:@"Button B" forState:UIControlStateNormal];
11:
12:     self.theLabel=[[UILabel alloc] init];
13:     self.theLabel.text=@"Welcome";
14:     [self updateInterface];
15: }

This might be the first time we’ve manually created a number of UI elements, but because you’ve been working with these objects and adjusting their properties for hours, this code shouldn’t seem completely foreign.

Line 2 initializes the buttonA property as a button of type UIButtonTypeRoundedRect—the standard button we use in our views. Lines 3–4 use the button’s addTarget:action:forControl Events method to choose what will happen when the Touch Up Inside event occurs for the button. The @selector directive specifies which method will be called during the event—such as handleButton. This is exactly the same as connecting a button to an IBAction in IB.

Line 5 sets the title for the button to Button A.

Lines 7–10 repeat the same process for Button B (buttonB).

Lines 12–13 allocate and initialize a label (theLabel) with the default text Welcome.

Lastly, line 14 invokes the updateInterface method so that the newly defined user elements can be placed on the screen. So, what do we do now? Implement updateInterface.

Implementing the Interface Update Method

The updateInterface method does the heavy lifting for the application. It checks to see what the current orientation is, and then it draws content based on the view’s bounds property. By basing the drawing on the height and width contained within bounds, you can scale to any screen size at all.

For example, consider this code snippet:

float screenWidth;
float screenHeight;
screenWidth=self.view.bounds.size.width;
screenHeight=self.view.bounds.size.height;

This grabs and stores the current screen width and height in the variables screenWidth and screenHeight. The dimensions and position of UI objects are determined by their frame, which is a property of type CGRect. To set the frame of a button property named theButton so that it filled the top half of the screen, I’d write the following:

self.theButton.frame=CGRectMake(0.0,0.0,screenWidth,screenHeight/2);

The first two values of CGRectMake (which create a CGRect data structure) set the origin point at 0,0. The second two parameters determine the width and height of the CGRect. Using screenWidth sets the button to the same width of the screen and screenHeight/2 sets the height of the button to half the height of the screen. In an actual implementation, you want to include some margin around the edges. This is why you’ll see +20 and other values tacked onto my coordinates. Speaking of which, go ahead and implement updateInterface, as shown in Listing 16.5. When you’re done, we step through the code.

Listing 16.5. The updateInterface Implementation

 1: - (void)updateInterface {
 2:     float screenWidth;
 3:     float screenHeight;
 4:     screenWidth=self.view.bounds.size.width;
 5:     screenHeight=self.view.bounds.size.height;
 6:
 7:     if (self.interfaceOrientation==UIInterfaceOrientationPortrait ||
 8:         self.interfaceOrientation==UIInterfaceOrientationPortraitUpsideDown) {
 9:         self.buttonA.frame=CGRectMake(20.0,20.0,screenWidth-40.0,
10:                                       screenHeight/2-40.0);
11:         self.buttonB.frame=CGRectMake(20.0,screenHeight/2+20,
12:                                       screenWidth-40.0,screenHeight/2-40.0);
13:         self.theLabel.frame=CGRectMake(screenWidth/2-40,
14:                                        screenHeight/2-10,200.0,20.0);
15:     } else {
16:         self.buttonA.frame=CGRectMake(20.0,60.0,screenWidth-40.0,
17:                                       screenHeight/2-40.0);
18:         self.buttonB.frame=CGRectMake(20.0,screenHeight/2+30,
19:                                       screenWidth-40.0,screenHeight/2-40.0);
20:         self.theLabel.frame=CGRectMake(screenWidth/2-40,20.0,200.0,20.0);
21:     }
22:
23:     [self.view addSubview:self.buttonA];
24:     [self.view addSubview:self.buttonB];
25:     [self.view addSubview:self.theLabel];
26: }

Lines 2–5 grab and store the current screen size in screenWidth and screenHeight.

Lines 7–8 checks the interfaceOrientation property of the view controller, and, if it is in one of the portrait orientations, lines 8–14 are executed. Otherwise, lines 16–20 are evaluated. These blocks both have the same purpose: defining the frame properties for each of the UI elements (buttonA, buttonB, and theLabel).

Lines 8–14 define positions for the buttons so that there are margins on the edges of the screen and a space in the middle for the label. Lines 16–20 position the buttons lower on the screen and put the label at the top. The margins and spacing I used is completely arbitrary. You can try changing these values around to see what effect they have.

Finally, lines 23–25 add the buttons and label to the view so that they are visible onscreen.

Everything is now in place for the interface, but we need to take care of three small tasks before the project is complete. First, we need to make sure that the interface is drawn when the application first loads. Second, the interface must update when an orientation change occurs. Third, we need to implement handleButton to update the label when the buttons are pressed.

Drawing the Interface When the Application Launches

When the application first launches, there isn’t an orientation change to trigger the interface to be drawn. To make sure there is something on the screen, we need to call initInterface when the application loads. Add this to viewDidLoad, as shown in Listing 16.6.

Listing 16.6. Initialize the Interface When the Application Loads

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initInterface];
}

We’re getting closer. The application will now initialize and display the interface, but it still can’t adapt to a change in orientation.

Updating the Interface When Orientation Changes

To handle orientation changes, the application needs to call updateInterface within an implementation of didRotateFromInterfaceOrientation. We also need to remove the existing buttons, otherwise the old version of the interface will still be visible; this is surprisingly easy to do.

Add didRotateFromInterfaceOrientation to ViewController.m, as shown in Listing 16.7.

Listing 16.7. Handle Rotation in didRotateFromInterfaceOrientation

1: - (void)didRotateFromInterfaceOrientation:
2:         (UIInterfaceOrientation)fromInterfaceOrientation {
3:     [[self.view subviews]
4:                 makeObjectsPerformSelector:@selector(removeFromSuperview)];
5:     [self updateInterface];
6: }

Lines 3–4 use the very cool makeObjectsPerformSelector method on all the subviews in the scene’s view (all of our UI elements) to send them the message removeFromSuperview. This, as expected, removes the buttons and label from the view.

Line 5 calls updateInterface and draws the appropriate version of the interface for whatever orientation we are currently in.

Handling the Button Touches

The last piece of the puzzle is implementing handleButton so that it updates the onscreen label with the label of the button being touched. This is just a single line, so add Listing 16.8 to the view controller, and you’re done.

Listing 16.8. Handle Button Touches

- (void)handleButton:(id)sender {
    self.theLabel.text=((UIButton *)sender).currentTitle;
}

The one line of the implementation uses the sender parameter (typecast as a UIButton) to grab the title of the button (currentTitle) that was pressed.

Building the Application

Build and run the application. It should rotate and resize with no problem. What’s more, because all of the interface layout was based on the height and width of the view, this same code will work, without changes, in an iPad or iPhone project.

I hope this didn’t scare you too much. The purpose of this exercise was to show that responsive and flexible interfaces can be accomplished in code without it being too much of a hassle. The biggest challenge is determining how the controls will be laid out and then coming up with the CGRectMake functions to define their locations.

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