Home > Articles > Programming > Mac and iOS Programming

  • Print
  • + Share This
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;


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];
 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];
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;

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:


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;
 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:     }
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.

  • + Share This
  • 🔖 Save To Your Account