Creating an iPhone Application – Tutorial Two

Posted on

Creating an iPhone Application – Tutorial Two

This is part two of an ongoing series of tutorials designed to teach you how to create an iPhone application.
This tutorial will guide you through the process of adding input and
output controls to an iPhone application and responding to user input
and touch events associated with these controls.
If you haven't already read the first tutorial, which explained how to create iPhone views,
then I suggest that you read it as a prerequisite, because it
introduces a number of key concepts that are critical to a complete
understanding of how iPhone applications work internally. It also
introduces you to basic use of Interface Builder, the view designer
application for iPhone.
This tutorial also assumes that you already have the working application
from tutorial one to use as a base. If you don't want to go through all
the steps in the first tutorial I provide a zip file containing the
complete code and project files. So before we get started you'll need
to download that zip file, or get ready to use your own copy of the code
from last week's tutorial.
Step One – Adding New Elements to the Application View
Currently, the only element in our application's view is a label that
says "Hello World." This is okay for a demo application that is
designed for the mere purpose of providing feedback to show that the
application view has loaded, but it's not very useful.
So let's add a few more complicated elements to the view.

  1. Open
    the XCode Project and double click on "HelloWorldView.xib", located in
    the "Resources" folder. This will launch Interface Builder, showing the
    design window, and the view's element hierarchy window.
  2. Open the Library toolbar by clicking Tools -> Library, or pressing ⌘ + + L.
  3. Now we want to add a "Round Rect Button" and a "Text Field" to the
    design window. Our goal is to create a view similar to the attached
    mockup. Drag one of each of these items over to the Design Window and
    release to place them.
  4. Now let's arrange the application view. Drag the "Hello World" to
    the bottom, then drag the button and text field above it. There is an
    important reason why the text field needs to be at the top of the
    screen. When the iPhone user clicks on the text field, the onscreen
    keyboard will open, and if the text field is on the bottom half of the
    screen, then it will be hidden by the keyboard.
  5. Make sure to resize the label so that it fills the lower half of the screen.
  6. Double click on the button and text field to edit their default text so that it matches the text in the mockup.
  7. For the text to show properly in the label you will have to adjust
    the properties of the label. By default it is set to clip text that
    sticks outside the bounds of the label. Change this by selecting the
    label, opening the Properties tab in the Inspector Window. Select "Word
    Wrap" line breaks, and change the maximum number of lines to zero,
    meaning there is no limit.

Basic iPhone Design Considerations
When you are designing the layout of elements for an iPhone view, it is
important to remember the main differences between desktop or laptop
computers and the iPhone. These differences are what make designing for
the iPhone different.
The first major difference is screen size. The iPhone screen, though
high resolution for a phone, is nowhere near as large as a laptop or
desktop screen. This means that there is less room for controls. If
you are not used to mobile application design then you will probably
need to completely rethink your interface design process. Applications
for the iPhone must be reduced to their most critical functionality, and
their most critical inputs, because these are all you will have room
for. If you try to shove too much onto the screen then you will simply
frustrate users.
The second major difference is the primary input mechanism. iPhone
owners must use their fingers for everything that they want to do on
their iPhone. This means that you can not have controls that are overly
small. A large fingertip is much less accurate than a mouse cursor, so
if you have a tiny toolbar with lots of small buttons users of your
application will probably get frustrated with trying to press these
small buttons. An important guideline is that buttons should not be
smaller than a fingertip.
These brief paragraphs only touch the tip of the iceberg when it comes
to designing for the iPhone. If you are interested in more on the
subject then I recommend that you read Apple's Human Interface
Guidelines for the iPhone. If you want to sell an application on the
app store it must meet these guidelines, so they are essential reading
for any iPhone developer.

Step Two – Linking the View Elements to the Application View Controller
At this point the elements are physically in the view, but if you
compile the program and run it they won't do anything. It is the job of
the view controller to add the methods for manipulating the view. In
the last tutorial we created a basic view controller called
HelloWorldViewController. It was extremely simple because all it had to
do was show the view. Now let's expand this view controller and link
our new elements to it.

  1. Save the view in Interface Builder and switch to Xcode.
  2. Open "HelloWorldViewController.h" and replace it's contents with the following lines of code:
    #import <UIKit/UIKit.h>
    @interface HelloWorldViewController : UIViewController{
    IBOutlet UITextField *text_input;
    IBOutlet UILabel *helloWorldLabel;
    IBOutlet UIButton *helloWorldButton;
    - (IBAction) buttonWasClicked:(id)sender;

    This is important because it defines three objects, one corresponding to each view element, and a method buttonWasClicked
    for responding to touches of the button element. At this point,
    though, these are just imaginary placeholders that do nothing. We have
    to link each of them to their respective real-world elements and events.

  3. Double-click "HelloWorldView.xib" to open the application view in Interface Builder again.
  4. Open the Inspector Window by clicking Tools->Inspector or by pressing ⌘ + + I.
  5. Open the connections tab of the Inspector Window, or press ⌘ + 2 to
    go directly to it. From this tab we can adjust the connections between
    elements in Interface Builder and code in Xcode.
  6. Select the button element by clicking on it.
  7. Locate the event "Touch Up Inside" in the Connections tab in the
    Inspector Window. This event corresponds with a user touching the
    button, then lifting their finger up to complete the button "click".
  8. Click on the round circle to the right of "Touch Up Inside" and drag
    the mouse over the Document Window where the element tree is shown. A
    blue line will appear between the "Touch Up Inside" event and the mouse
    cursor. Release the mouse button over the "File's Owner" element in the
    Document Window.
    Click on the screenshot to enlarge it.
  9. A small popup box will appear listing the methods of the
    HelloWorldViewController class, which is the owner class for this view.
    At this point there is only one method, which happens to be the very
    one we want. Click on "buttonWasClicked:" to select this method.
  10. A new connection will be formed linking the event to your code. In the Inspector window the new connection will look like this:
  11. Now let's create connections between the other elements and their
    code outlet counterparts. Click on File's Owner in the Document Window.
  12. In the Connections tab you will see a list of the code outlets
    appear. These are the properties that we created for our
    HelloWorldViewController object.
  13. Create a connection between the outlet "text_edit" and the text edit
    element by clicking on the circle and dragging the blue line over the
    text edit element. You can drag the end of the line either over the
    element's entry in the Document Window, or you can drag it over to the
    text edit element as it appears in the Design Window. A new connection
    will form linking this element with the code object.
  14. Repeat the same process for "helloWorldLabel" and
    "helloWorldButton," linking each code outlet with its respective
    element. When you are done "File's Owner" will have the following

Step Three – Implementing the View Controller Methods
At this point the elements are created, and linked to the controller.
But our method for handling touch events on the button is nothing but a
stub. We need to flesh out this method.

  1. Save the application view in Interface Builder and switch to Xcode.
  2. Open HelloWorldViewController.m in Xcode and replace it's contents with the following lines of code:
    #import "HelloWorldViewController.h"
    @implementation HelloWorldViewController
    - (IBAction) buttonWasClicked:(id)sender {
    NSString *enteredText = text_input.text;
    NSString *Message = nil;
    if([enteredText length] == 0)
    Message = [[NSString alloc] initWithFormat:@"You didn't enter anything!"];
    Message = [[NSString alloc] initWithFormat:@"You entered: %@", enteredText];
    helloWorldLabel.text = Message;
    //Release the object
    [Message release];
    - (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
    - (void)dealloc {
    [text_input release];
    [helloWorldLabel release];
    [helloWorldButton release];
    [super dealloc];

    The view controller's implementation now includes two basic functions to
    handle memory allocation and warnings, and the core method which
    responds to the button touch event. The "buttonWasClicked:" method uses
    the code outlets we created earlier to grab the text out of the text
    edit element. It then sets the contents of the label to the contents of
    the text edit element.

  3. Save the file and build and run the application. Everything works
    fine right up until you enter the text in the text edit element. When
    you click "Done" on the onscreen keyboard nothing happens. This is
    because we are missing an important event. The event to open the
    onscreen keyboard happen automatically when the text edit element is
    touched, but if we want the keyboard to go away we have to close it
  4. Once again we must open the application view in Interface Builder.
  5. Select the text edit element, and open the Inspector Window to the connections tab.
  6. Create a connection between the outlet "delegate" and "File's Owner"
    just as you did before. Creating this connection allows the
    HelloWorldViewController to receive messages associated with the text
    edit element. The connection will look like this:
  7. Save the view and return to "HelloWorldViewController.m" in Xcode.
  8. Add the following implementation to the object:
    - (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    [theTextField resignFirstResponder];
    return YES;

    Every time the "Done" button on the onscreen keyboard the message
    textFieldShouldReturn is called in association with the text edit
    element. Since HelloWorldViewController is a delegate for the text
    element it will now receive the message and return "YES" indicating that
    the onscreen keyboard should close.

  9. Save the file and build and run the application.

Testing and Troubleshooting
completed application should look similar to the attached screen shot.
When the user clicks on the text edit element the onscreen keyboard
should open, and when the user finishes entering text and presses "Done"
the keyboard should close. When the user presses "What did I type?"
the application should display the entered text.
If your application crashes then you need to inspect all the
connections. If any of them are missing or linked incorrectly then the
code will crash because it will not be able to access the element or it
will be accessing the wrong element. A crash typically means that you
dragged the connection line over to the wrong element by accident.
If the application works correctly, but the onscreen keyboard does not
close when you press Done then that means that you did not create the
connection between the text edit's "delegate" and "File's Owner." If
this connection isn't existent then you code will know nothing about
user's request to close the keyboard.
This simple application shows how to add more complex elements to an
iPhone application view and respond to events associated with them.
Using this application as a starting point you should be able to create
just about any single view application that you want. All it involves
is adding the elements in Interface Builder and then creating the
connections between the elements and events, and their respective
objects and methods. If you want to use different elements or use them
in different ways Apple documentation will supply you with the full
methods and properties of each element type.
Download the Xcode Project for Tutorial Two
Creating an iPhone Application – Tutorial Two

Rating: 4.5
Diposkan Oleh:
Nurul Hamdi

Share ke:


Artikel Terkait Creating an iPhone Application – Tutorial Two :

Pencarian Terakhir:

Tinggalkan Balasan

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *