Creating an Interactive iOS 7 App

From Techotopia
Revision as of 20:14, 17 October 2013 by Neil (Talk | contribs) (New page: In the previous chapter we looked at the design patterns that we will need to learn and use regularly in the course of developing iOS 7 based applications. In this chapter we will work t...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search


In the previous chapter we looked at the design patterns that we will need to learn and use regularly in the course of developing iOS 7 based applications. In this chapter we will work through a detailed example intended to demonstrate the View-Controller relationship together with the implementation of the Target-Action pattern to create an example interactive iOS 7 based iPhone application.


Contents


Creating the New Project

The purpose of the application we are going to create is to perform unit conversions from Fahrenheit to Centigrade. Obviously the first step is to create a new Xcode project to contain our application. Start Xcode and on the Welcome screen select Create a new Xcode project. On the template screen choose the Application option located under iOS in the left hand panel and select Single View Application. Click Next, set the product name and class prefix to UnitConverter, enter your company identifier and make sure that the Devices menu is set to iPhone. On the final screen, choose a location in which to store the project files and click on Create to proceed to the main Xcode project window.

Creating the User Interface

Before we begin developing the logic for our interactive application we are going to start by designing the user interface. When we created the new project, Xcode generated a storyboard file for us and named it Main.storyboard. It is within this file that we will create our user interface, so select this file from the project navigator in the left hand panel to load it into Interface Builder. Once Interface Builder has loaded the file, select the View -> Utilities -> Show Object Library menu option:


The main Xcode 5 window

Figure 11-1


From the Object Library panel, drag a Text Field object onto the View design area. Resize the object and position it so that it appears as outlined in Figure 11-2.


Ios 7 unitconverter textfield.png

Figure 11-2


Within the Attributes Inspector panel (View -> Utilities -> Show Attributes Inspector), type the words Enter temperature into the Placeholder text field. This text will then appear in a light gray color in the text field as a visual cue to the user. Since only numbers and decimal points will be required to be input for the temperature, locate the Keyboard property in the Attributes Inspector panel and change the setting to Numbers and Punctuation.

Now that we have created the text field into which the user will enter a temperature value, the next step is to add a Button object which may be pressed to initiate the conversion. To achieve this, drag and drop a Button object from the Library to the View. Double click the button object so that it changes to text edit mode and type the word Convert onto the button. Finally, select the button and drag it beneath the text field until the blue dotted line appears indicating it is centered horizontally in relation to the text field before releasing the mouse button.

The last user interface object we need to add is the label where the result of the conversion will be displayed. Add this by dragging a Label object from the Object Library window to the View and position it beneath the button. Stretch the width of the label so that it is approximately a third of the overall width of the view and reposition it using the blue guidelines to ensure it is centered in relation to the button. Modify the Alignment attribute for the label object so that the text is centered.

Double click on the label to highlight the text and press the backspace key to clear it (we will set the text from within a method of our View Controller class when the conversion calculation has been performed). Though the label is now no longer visible it is still present in the view. If you click where it is located it will be highlighted with the resize dots visible.

At this point the user interface design phase of our project is complete and the view should appear as illustrated in Figure 11 3. We now are ready to try out a test build and run. <google>ADSDAQBOX_FLOW</google>


The user interface layout for the unit converter app

Figure 11-3



Building and Running the Sample Application

Before we move on to implementing the controller code for our application and then connecting it to the user interface we have designed we should first perform a test build and run of the application so far. Click on the Run button located in the toolbar (the triangular “play” button) to compile the application and run it in the simulator. If you are not happy with the way your interface looks feel free to reload it into Interface Builder and make improvements. Assuming the user interface appears to your satisfaction in the simulator we are ready to start writing some Objective-C code to add some logic to our controller.

Adding Actions and Outlets

When the user enters a temperature value into the text field and touches the convert button we need to trigger an action which will perform a calculation to convert the temperature. The result of that calculation will then be presented to the user via the label object. The Action will be in the form of a method which we will declare and implement in our View Controller class. Access to the text field and label objects from the view controller method will be implemented through the use of Outlets.

Before we begin, now is a good time to highlight an example of the use of subclassing as previously described in An Overview of the iOS 7 Application Development Architecture. The UIKit framework contains a class called UIViewController which provides the basic foundation for adding view controllers to an application. In order to create a functional application, however, we inevitably need to add functionality specific to our application to this generic view controller class. This is achieved by subclassing the UIViewController class and extending it with the additional functionality we need.

When we created our new project, Xcode anticipated our needs and automatically created a subclass of UIViewController and named it UnitConverterViewController (using the class prefix entered when the project was initially created). In so doing, Xcode also created two source files; a header file named UnitConverterViewController.h and a source code file named UnitConverterViewController.m.

Selecting the UnitConverterViewController.h file in the Xcode project navigator panel will display the contents of the file in the editing pane:

#import <UIKit/UIKit.h>

@interface UnitConverterViewController : UIViewController 
@end

As we can see from the above code, a new class called UnitConverterViewController has been created that is a subclass of the UIViewController class belonging to the UIKit framework.

The next step is to extend the subclass to include the two outlets and our action method. This could be achieved by manually declaring the outlets and actions within the UnitConverterViewController.h file. A much easier approach is to use the Xcode Assistant Editor to do this for us.

With the Main.storyboard file selected, display the Assistant Editor by selecting the View -> Assistant Editor -> Show Assistant Editor menu option. Alternatively, it may also be displayed by selecting the center button (the one containing an image of a bow tie and tuxedo) of the row of Editor toolbar buttons in the top right hand corner of the main Xcode window as illustrated in the following figure:


The Xcode 5 view menu

Figure 11-4


In the event that multiple Assistant Editor panels are required, additional tiles may be added using the View -> Assistant Editor -> Add Assistant Editor menu option.

By default, the editor panel will appear to the right of the main editing panel in the Xcode window. For example, in Figure 11-5 the panel to the immediate right of the Interface Builder panel is the Assistant Editor:


The Xcode 5 Assistant Editor displayed

Figure 11-5


By default, the Assistant Editor will be in Automatic mode, whereby it automatically attempts to display the correct source file based on the currently selected item in Interface Builder. If the correct file is not displayed, use the toolbar along the top of the editor panel to select the correct file. The small instance of the tuxedo icon in this toolbar can be used to switch to Manual mode allowing the file to be selected from a pull-right menu containing all the source files in the project.

Make sure that the UnitConverterViewController.h file is displayed in the Assistant Editor and establish an outlet for the Text Field object by ctrl-clicking on the Text Field object in the view and drag the resulting line to the area immediately beneath the @interface directive in the Assistant Editor panel as illustrated in Figure 11-6:


Working with the Assistant Editor to establish an outlet in Xcode 5

Figure 11-6


Upon releasing the line, the configuration panel illustrated in Figure 11 7 will appear requesting details about the outlet to be defined.


Establishing an outlet connection in Xcode 5

Figure 11-7


Since this is an outlet, the Connection menu should be left as Outlet. The type and storage values are also correct for this type of outlet. The only task that remains is to enter a name for the outlet, so in the Name field enter tempText before clicking on the Connect button.

Once the connection has been established, select the UnitConverterViewController.h file and note that the outlet property has been declared for us by the assistant:

#import <UIKit/UIKit.h>

@interface UnitConverterViewController : UIViewController 

@property (strong, nonatomic) IBOutlet UITextField *tempText;
@end

Repeat the above steps to establish an outlet for the Label object named resultLabel.

Next we need to establish the action that will be called when the user touches the Convert button in our user interface. The steps to declare an action using the Assistant Editor are essentially the same as those for an outlet. Once again, select the Main.storyboard file, but this time Ctrl-click on the button object. Drag the resulting line to the area beneath the two new IBOutlet lines in the Assistant Editor panel before releasing it. The connection box will once again appear. Since we are creating an action rather than an outlet, change the Connection menu to Action. Name the action convertTemp and make sure the Event type is set to Touch Up Inside:


Configuring an Action connection in Xcode 5

Figure 11-8


Click on the Connect button to create the action.

Select the UnitConverterViewController.h file and note that the action has now been declared for us by the assistant:

#import <UIKit/UIKit.h>

@interface UnitConverterViewController : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *tempText;
@property (strong, nonatomic) IBOutlet UILabel *resultLabel;
- (IBAction)convertTemp:(id)sender;
@end

Next, select the UnitConverterViewController.m file and note that a stub method for the action has also been added automatically by the Assistant Editor:

- (IBAction)convertTemp:(id)sender {
}

All that remains, therefore, is to implement the code in the action method to perform the conversion:

- (IBAction)convertTemp:(id)sender {
    double fahrenheit = [_tempText.text doubleValue];
    double celsius = (fahrenheit - 32) / 1.8;

    NSString *resultString = [[NSString alloc]
                              initWithFormat: @"Celsius %f", celsius];
    _resultLabel.text = resultString;
}

Before we proceed it is probably a good idea to pause and explain what is happening in the above code. Those already familiar with Objective-C, however, may skip the next few paragraphs.

In this file we are implementing the convertTemp method, a template for which was created for us by the Assistant Editor. This method takes as a single argument a reference to the sender. The sender is the object that triggered the call to the method (in this case our Button object). Whilst we won’t be using this object in the current example, this can be used to create a general purpose method in which the behavior of the method changes depending on how (i.e. via which object) it was called. We could, for example, create two buttons labeled Convert to Fahrenheit and Convert to Celsius respectively, each of which calls the same convertTemp method. The method would then access the sender object to identify which button triggered the event and perform the corresponding type of unit conversion.

Next, the code declares a variable of type double in order to handle the fact that the user may have entered a floating point value. We then use dot notation to access the text property (which holds the text displayed in the text field) of the UITextField object. By convention this object is referenced using the property name declared for the outlet prefixed with an underscore character (in this case _tempText). This property is itself an object of type NSString. The NSString class has an instance method named doubleValue that converts the string value to a double. We therefore call this method on the text property and assign the result to our Fahrenheit variable.

Having extracted the text entered by the user and converted it to a number, we then perform the conversion to Celsius and store the result in another variable named celsius. Next, we create a new NSString object and initialize it with text comprising the word Celsius and the result of our conversion. In doing so, we declare a pointer to this new object and call it resultString.

Finally, we use dot notation to assign the new string to the text property of our UILabel object so that it is displayed to the user.

Building and Running the Finished Application

From within the Xcode project window click on Run to compile the application and run it in the simulator. Once the application is running, click inside the text field and enter a Fahrenheit temperature. Next, click on the Convert button to display the equivalent temperature in Celsius. Assuming all went to plan your application should appear as outlined in the following figure (note that if the keyboard obscures the result label you will need to reload the user interface design into Interface Builder and move the label, button and text field objects so that they are all positioned in the top half of the view):


An example interactive iOS 7 App running

Figure 11-9


Summary

In this chapter we have put into practice some of the theory covered in previous chapters, in particular the separation of the view from the controller, the use of subclassing and the implementation of the Target-Action pattern through the use of actions and outlets.

You may have noticed whilst testing your application that once the keyboard is displayed it doesn’t then go away even when you touch the Return key or any other area on the screen. In order to make the keyboard disappear we need to write some code. The next chapter, entitled Writing iOS 7 Code to Hide the Keyboard provides a tutorial on how to hide the keyboard when either the keyboard Return key or the background view are touched by the user.