Docstoc

HKUSpace-iPhone-Dev-Tutorial-1

Document Sample
HKUSpace-iPhone-Dev-Tutorial-1 Powered By Docstoc
					      Tutorial 1: Familiar with iPhone App Development


Overview
1. Introduction

2. Creating a New iPhone App Project
2.1 Creating a New iPhone App Project using Xcode
2.2 Changing Various iPhone App Settings

3. Adding UI Components onto Screen View by using Interface Builder
3.1 Adding VolcanoRockEscapingView.h and .m to Classes Folder in Xcode
3.2 Modifying VolcanoRockEscapingViewController.xib
3.3 Adding in All Other UI Components

4. Connecting UI Components with IBOutlets
4.1 Defining an IBOutlet
4.2 Defining an IBAction
4.3 Connecting the IBOutlet with the UIComponent
4.4 Connecting the IBAction with the action of UIComponent
4.5 Other IBOutlets
4.6 Write to the VolcanoRockEscapingViewController Files

5. Implementing the Facebook Button Pressed Function and the “Shake” Function
5.1 Facebook Button Pressed Detection
5.2 Shake Detection
5.3 Variable and Function Declarations
5.4 Function Implementation
5.5 Calling initializeData
5.6 Run and Debug
5.7 Simple Exercise




                                                                                1
1. Introduction
In this tutorial session, we would like to introduce the procedures in developing an iPhone app from
scratch. You will be able to learn:
a. How to create a new iPhone app project
b. How to add UI components (e.g., Image, Text, etc.) onto the screen view (iPhone’s display)
c. How to establish a connection between a UI component created in Interface Builder with a
    variable (IBOutlet) in the view controller
d. How to establish a connection between an action on a UI component (e.g., press a button) to a
   function (IBAction) in the view controller


The whole lab exercise is divided into four main parts:
1. Creating a new iPhone app project
2. Putting UI components onto the screen view by using Interface Builder
3. Connecting the UI components with the outlets and connecting an action on a UI component
   (e.g., press a button) with a function.
4. Implementing a simple button pressed function and a simple shake function



2. Creating a New iPhone App Project
The goal of this part is to allow the students to get familiar with the Xcode and the procedures in
developing an iPhone app through the creation of a new iPhone app project, and modifying various
property settings.



2.1 Creating a New iPhone App Project using Xcode
The following describes detailed steps to create a new iPhone app project using Xcode:
i.      Open Xcode:

       a. Press the         icon on the right upper corner of the Desktop.

       b. Type in “Xcode” in the blank text field block next to “Spotlight”.



       c. Click on Xcode from the pull down menu shown.



                                                                                                  2
        d. Xcode window will then pop up (see next page for the screenshot).




ii.     Create a new Xcode project
      a. Click on “Create a new Xcode project”




      b. A new project creation window will pop up like this:




                                                                               3
       c. Here, we will develop an iOS Application, and use View-based Application template.



          Therefore,   click   on               icon   and   set   the   product   to     iPhone,    i.e.,



                                                . Then, click on the Choose button                     at
          the right bottom corner of the window.
       d. Now, a window will be popped up to ask for the name of the project. Here, we would like
          everyone to use “VolcanoRockEscaping”.




          Click on Save button afterwards.
       e. You have created the project successfully. The following window will then be shown.




iii.     Xcode usage
       a. To expand the folder under the Groups & Files, you can click on the           icon next to the

          folder. That is, after you click on      icon next to the Classes folder                  , the

          following files will be shown (see next page):


                                                                                                        4
b. Expanding the folders under Group & Files, you will see a list of files automatically created
   for you during project creation.




Basically, we are only interested in the following files in this app development:
   1. Interface Builder File: “VolcanoRockEscapingViewController.xib”,
   2. Code Logic Files: “VolcanoRockEscapingViewController.h”, and
   3. “VolcanoRockEscapingViewController.m”
c. Try clicking on the “VolcanoRockEscapingViewController.m” file, the corresponding codes
   inside will be shown in the text editor region.




                                                                                              5
      d. Now, we will try compile and run the app to have a look of the results. But before that we
         first set the target running location of the app.

         You can select it by clicking                                               which is located
         above the Groups & Files windows. A pull down menu will then be shown up as follows:




         Here, you can (i) load your app to real device by selecting Device or (ii) load your app to
         simulator by selecting simulator. Please be reminded that we will use iPhone simulator
         during this workshop unless specified.



      e. You can compile and run the app by clicking                       icon which is located just
          under the project title. Then, your app will be started in the target device selected in (d).
iv.     iPhone Simulator Usage
      a. After clicking the Build and Run icon, the iPhone simulator will be prompted up
          automatically. Since we have not done anything to the screen display, only a blank screen
          with a status bar will be shown.

                                                                                         App Icon



      Status Bar


      Home
      Button




                                                                                                     6
      b. Now, you can try moving your mouse to the home button of the iPhone simulator and then
         click it. You can find your app with a blank icon shown on the desktop of the iPhone
         simulator.



2.2 Changing Various iPhone App Settings
In previous sections, we have walked through detailed procedures in creating a new iPhone app
project, and tested the newly created app in the iPhone simulator. In this part, we would like to
introduce the methods in changing various common project settings, such as, (i) hidden the status
bar, (ii) the orientation of the app, (iii) the icon of the app, and (iv) the launch image, etc.


In fact, all the functions mentioned above can be set by modifying the project information property
list. In this project, the file is “VolcanoRockEscaping-info.plist”. Now, you can click the file, and then
you will see a list of items shown on the text editor.




Here, each row represents a property that you can set to the app. We will now discuss how to set
various properties:


i.   Hidden Status Bar
      i. Highlight the “Information Property List” row


                                                                                                        7
      ii. Control-Click the row (Note that Control is a key on the Mac keyboard)
      iii. A list will be popped up for you to add a new row to the property list




      iv. Select the item “Status bar is initially hidden” in the pull down menu.
      v. Check the box on the right hand side.




      vi. Now, you can compile and run the app by clicking                     icon, and see the result
           in the iPhone simulator.
      vii. You can see that the status bar shown in the iPhone simulator disappears.


ii.     App Orientation
      By default, all iPhone apps are set to the portrait orientation with the home button at the
      bottom, i.e., the orientation currently shown on the iPhone simulator.
      a. Similar to (i)(a) – (c)
      b. Select the item “Supported interface orientations”
      c. Click on the      icon next to the “Supported interface orientations”. A new row of item
         will be shown.



      d. Click on the “Portrait (bottom home button)” column in the new row of item shown, a pull
         down menu will appear.
      e. Now, select “Landscape (right home button)”



      f. Click on the “VolcanoRockEscapingViewController.m” file
      g. Look for the codes “shouldAutorotateToInterfaceOrientation”
      h. Change the codes inside to the following:


                                                                                                     8
        i.   Now, you can compile and run the app by clicking                   icon, and see the result
             in the iPhone simulator.
        j.   The simulator will turn to Landscape orientation with the home button on the right hand
             side.


iii.      Changing App Icon
       Note that an icon should be a 57 x 57 pixels graphic file. Before we can change the icon, we must
       provide a list of graphics to the project.
       a. Download the “volcano_graphics.zip” from our website and put the file to Desktop.
       b. Double-click the zip file to unzip. A volcano_graphics folder will be created.
       c. For your convenience (our convenience also :), drag all the files inside the volcano_graphics
          folder to the resource folder in Xcode.




       d. A window will then be popped up. Here, remember to check the box “Copy items into
          destination group’s folder” before clicking the add button. Otherwise, Xcode will only store
          up the reference to the files instead of copying the files to the project folder.


                                                                                                      9
      e. Go back to the “VolcanoRockEscaping-info.plist” file, and look for the row “Icon file”
      f. Click on the blank column on the right hand side of the row “Icon file”, and type in the file
         name of the icon, i.e., “volcano-icon.png”




      k. Now, you can compile and run the app by clicking                     icon, and see the result in
         the iPhone simulator. (Please note that you have to click on the home button on the iPhone
         simulator to see the effect).


iv.      Setting the launch image
       a. Add a new row similar to (i) and (ii).
       b. Find the name “Launch Image” in the pull down menu.
       c. Change the name of the file to “volcano.png” similar that of (iii)(f) above.
       d. Compile.
       e. See the result.




                                                                                                      10
3. Adding UI Components onto Screen View by using


Interface Builder

The goal of this part is to put different UI components, e.g., images, texts, etc., onto the screen view
to develop a display as follows:
                                                          UILabel
                                                                                UIButton




         UIImageView




Generally speaking, UI components are something that can be visually displayed on the screen view.
We first introduce some commonly used UI components:
i.   UILabel – This component is mainly used to display some texts on the screen. You can specify
     the text string, size of the fonts, font color, font type, etc., using Interface Builder.
ii. UIImageView – This component is mainly used to display an image on the screen. Interface
     Builder allows users to set the image, center position, frame size, set hidden or visible, etc.
iii. UIButton – Different from a label or an image, a button can be pushed. That is, some actions,
     such as “touch inside up”, can be done to this UI component. User can specify what should be
     done when a “touch inside up” event is detected.


For more details on UI components and screen view, please refer to the Lecture Notes.




                                                                                                      11
3.1 Adding VolcanoRockEscapingView.h and .m to Classes

Folder in Xcode
In this app, we will support “shake” function. Unfortunately, the default view does not support this
function. To support it, we have provided you with a customized view which will be added in the
screen view with the use of Interface Builder. Before that, you have to:
i.   Download the VolcanoRockEscapingView.h and VolcanoRockEscapingView.m from our website.
ii. Copy the files to the Classes folder in Xcode (similar to adding graphic files to the Resources
    folder before).



3.2 Modifying VolcanoRockEscapingViewController.xib
As mentioned before, when you create a view-based application, several files will be generated for
you automatically. They are <project name>ViewController.h, <project name>ViewController.m, and
<project name>ViewController.xib. As the project we are working on is called VolcanoRockEscaping,
you will find “VolcanoRockEscapingViewController.h”, “VolcanoRockEscapingViewController.m”, and
“VolcanoRockEscapingViewController.xib” under the project.


By default, the application will invoke the “VolcanoRockEscapingViewController.xib”, which
describes the UI components on the screen, during the startup time. Therefore, we can modify this
file to change the view of the screen by using Interface Builder. After opening the xib file, several
windows will be shown as follows:


Tips: Note that Xcode and Interface Builder are two different kinds of software. They may open
several windows. If you are not sure which software is the active one, check out the top left hand
side of the menu bar. You should find the name of the active software next to the Apple icon.




                                                                                                  12
Make sure you have the following windows. If any one of these is closed by accident, you can refer
to the instructions below to open it again.
    Library (use the Classes tab)
      - open through Tools -> Library from the Menu bar
    View (design the display of your game here)
      - open through double clicking View inside VolcanoRockEscapingViewController.xib window
    View Attributes
      - open through Tools -> Attributes Inspector from the Menu bar
    VolcanoRockEscapingViewController.xib
      - open through double clicking the file name VolcanoRockEscapingViewController.xib


Previously, you may have hidden the status bar and change the orientation with the use of
information property list. However, as explained in notes, xib file is loaded during the startup of
the application. Therefore, it does not have any information about whether you have changed the
property list information or not.


Before we go through the process of adding UI component onto the screen view, first of all, we will
describe the process of changing the current screen view to our customized view.


i.   Customized Screen View – VolcanoRockEscapingView


                                                                                                 13
a. Highlight the           inside the window:




b. Choose               icon in the Attribute window.
c. Change the Class field from “UIView” to “VolcanoRockEscapingView”:




d. If succeeded, you can see that the original          icon change to           icon.

e. Click on the              icon in the Attributes Window. Resize the view by modifying the
   size and position attributes. Note that the size for portrait mode is W:320 H:480




                                                                                         14
      f. Finally, clicking               icon in the Attributes Window, and set the view to landscape
          by    selecting    landscape     in   the   pull   down    menu     of   the   Orientation




Now, we will go through the process of adding the background UIImageView, the fire UIImageView
(the fire image on top of volcano), the “Life :” UILabel on left upper corner of the view.


Basically, the general procedure of adding something on View is as follows:
   Identify the type of component, such as image, button, etc., you want to add in the Library
    window
   Drag it on View, resize if necessary
   Modify the attributes in the Attributes window. You can specify what image to be display for a
    component there as well.


ii. Background UIImageView
     1. Drag a UIImageView Component from Library to the View screen so that it covers the
        whole screen.




     2. Select the “bg.png” from the Image pull down menu in the Image View Attributes Window
        shown on the right hand side.
     3. After that, the background image is shown as follows:


                                                                                                   15
iii. Fire UIImageView
      1. Again, drag a UIImageView to the View.
      2. However, we will also set the position and size of the UIImageView from the Image View
          Size tab in the Attributes window. Here, we set X: 197, Y: 39, W: 65, H:84. (Please note that
        the X, Y coordinates here refer to the point shown as red in the square. All the points that
        we are considering in the Interface Builder now is the origin, i.e., the left upper corner)




     3. Afterwards, the Image can be set to “fire.png” similar to that of before.


iv. “Life :” UILabel
     1. Now, drag a UILabel from Library window to the view.
     2. Change the text Form “Label” to “Life :”. Note that you can change the text by either (a)
        single click the label (b) change the text in the label attribute.
     3. Change the font type to “Verdana Italic” with size 20.
     4. Similar to (ii), set the position of the UILabel to X:3, Y:0, W:65, H:28




                                                                                                    16
Now save the file in Interface Builder. We are about to run our first program! First, go back to
Xcode (by clicking the Xcode icon in the bottom tool bar). Click the “Run and Debug” button in
the Xcode. It will launch the iPhone simulator and it will look like this (see next page):




                                                                                             17
3.3 Adding in All Other UI Components
      Please add in all other components listed in the table in sequence order:



                                           iv        v     vi        vii        viii
           i


          ii
                                                                                                   ix
         iii




Number         Component        Property                        X          Y           W     H
i              UIImageView      Image “life.png”                59         0           26    26
ii             UIImageView      Image “life.png”                86         0           26    26
iii            UIImageView      Image “life.png”                113        0           26    26
iv             UILabel          Font size 20, Font              152        0           74    28
                                “Verdana Italic”
v              UILabel          Font size 20, Font          244            0           60    28
                                “Verdana Italic”, alignment
                                center
vi             UILabel          Font size 20, Font              299        0           67    28
                                “Verdana Italic”
vii            UILabel          Font size 20, Font          370            0           60    28
                                “Verdana Italic”, alignment
                                center
viii           UIButton         Type Custom                     447        1           30    30
                                Image
                                “facebook-icon.png”
ix             UIImageView      Image “volcano.png”             0          80          480   240
      After you have put in everything, you should get the following (see next page) when you run it.



                                                                                                        18
4. Connecting UI Components with IBOutlets
It is very often that the status/property (e.g., position, text value, etc.) of a UI component changes
when the app is running. To allow the codes to specify how a UI component changes, we need a
way to specify this UI component in the codes. We call this procedure “connect the UI component
to an IBOutlet”.


4.1 Defining an IBOutlet
i.     Find out the “VolcanoRockEscapingViewController” in the Library.
ii.    Select “Outlets” in the pull down menu (this shows what outlets have been defined in the
       project).
iii.   Press the “+” button in the lower left hand corner of the window (it means you want to add
       a new outlet).
iv.    Input “scoreLabel” on the left hand side and “UILabel” on the right hand side (this step
       defines the IBOutlet variable called “scoreLabel” and it is going to represent a UILabel
       component with value “0”).




                          .
                                                                                                   19
4.2 Defining an IBAction
       i.     Find out the “VolcanoRockEscapingViewController” in the Library.
       i.     Select “Actions” in the pull down menu (this shows what actions have been defined
              in the project).
       ii.    Press the “+” Button in the lower left hand corner of the window (it means you want
              to add a new action).
       iii.   Input “facebookButtonPressed:” (don’t miss the colon!) on the left hand side and “id”
              on the right hand side. This step defines the IBAction function name and input
              parameter.




                              .


4.3 Connecting the IBOutlet with the UIComponent
We now specify which UI component a certain IBOutlet variable stands for. In the following, we
connect the newly defined IBOutlet “scoreLabel” to the text label (“0”) in View (as shown in the
figure below).
i.    Control-click the File’s Owner.
ii.   Drag from the empty circle next to the “scoreLabel” to the UILabel (“0”) on the screen (see
      next page).




                                                                                               20
                                                                 UILabel (“0”)




              Drag from here to there




4.4 Connecting the IBAction with the action of UIComponent
    We now specify the newly defined IBAction “facebookButtonPressed:” responding to
    pushing the facebook button.
    i.     Control-click the UIButton (facebook-icon.png).
    ii.    Drag from the empty circle next to the “Touch Up Inside” to the File’s Owner.
    iii.   Then, select                     shown up.




                                                                                      21
4.5 Other IBOutlets
      Create other IBOutlets listed in the table below:
       Type        Variable/function name       UIComponent       Image of the
                                                type              UIComponent connected
                                                                  to
       IBOutlet    life1Image                   UIImageView       life.png
       IBOutlet    life2Image                   UIImageView       life.png
       IBOutlet    life3Image                   UIImageView       life.png
       IBOutlet    timeLabel                    UILabel           (N/A)
       IBOutlet    volcanoImage                 UIImageView       volcano.png


Tips: You can check out a summary of all the IBOutlets and IBActions you have defined and
connected by control-click “Files’ Owner” in the VolcanoRockEscapingViewController.xib window.
The pop-up box will look like this:



                                                                     IBOutlets connected




                                                                    IBActions connected




4.6 Write to the VolcanoRockEscapingViewController Files
When you define IBOutlets and connect them to the UIComponents in Interface Builder, the
changes cannot be seen in the codes (.h and .m files) yet. We have to specify how to change the
codes by
i.     Highlight File’s Owner
ii.     Select File -> Write Class Files from the File menu bar




                                                                                             22
iii.     Select Save




iv.      Select Merge




       We select “Merge” because we want to specify which code fragments to be added in the
       original .h and .m files. (From now on, we simply use .m and .h to refer to
       VolcanoRockEscapingViewController.m  and    VolcanoRockEscapingViewController.h   for
       simplicity.)


v.       Select the code fragments to be included into the merged files:


                                                                                          23
      Two     windows,      one    for    VolcanoRockEscapingViewController.h       and    one     for
      VolcanoRockEscapingViewController.m will be opened. For both of them, the left hand side
      shows version edited by the Interface Builder (after you define IBOutlets, and IBActions), while
      the right hand side provides the original file, as shown below.




                              VolcanoRockEscapingViewController.h




                              VolcanoRockEscapingViewController.m


      Differences are highlighted light blue with arrows pointing to either left or right. The code
      fragments being pointed are the selected version to be used. For example, we defined IBOutlet
      “scoreLabel” using Interface Builder. Thus, we can find the method on the left hand side of
      VolcanoRockEscapingViewController.h window. We want this variable to be included in the
      final version, and so the arrow should be pointing to the left hand side.


vi.     Save the merged results by selecting File -> Save Merge in the menu bar before closing
        the .m and .h windows.

5. Implementing the Button Pressed Function and the

“Shake” Function
In this part, we are going to implement the features: When the user presses the facebook button,
“Score” is one more, while “Time Elapsed” is also one more. On the other hand, when the user
shakes the device, “Score”, and “Time Elapsed” restore to zero. We need to develop codes for the
following:



                                                                                                   24
1.   make sure that your app respond to the facebook button pressed
2.   make sure that your app respond to “shake”
3.   define variables for keeping “Score” and “Time Elapsed”
4.   modify the variables when the button pressed is detected
5.   display new results on the screen
6.   simple exercise – modify the variables when shake is detected and display the results on the
     screen.


5.1 Facebook Button Pressed Detection
Recall that in Sections 4.2 and 4.4, we have defined and connected the button pressed action to
“facebookButtonPressed:” function. Therefore, the following function should appear in the
VolcanoRockEscapingViewController.m file.




In fact, the braces contain the pieces of the codes that will be run when you press the    button.
Now, we would like you to type in the following NSLog() statement in-between the braces:

                    NSLog(@"Shaking Detected"); pressed");
                         NSLog(@"facebook button



Finally, you can see the following result in the console:




NSLog is a function which takes in Objective-C String as input and will output the result to the
console. There are two ways in opening the console in Xcode:


1. Select Run -> Console




                                                                                                25
2. Press the         icon




Now, you can click                  icon to compile and run the app in iPhone simulator.



5.2 Shake Detection
The goal of replacing the original view with a customized view in Section 2 is to facilitate the shake
detection detailed in this section. To fully enable this function, we still need to add in two functions
inside the VolcanoRockEscapingViewController.m file. Unlike normal function that we will discuss in
next part, we do not need to explicitly declare these two functions in .h.


Therefore, you can simply copy the codes shown below to your .m file (any place after
@implementation, and before @end).




You can see that the braces contain a line “// Shake Detected”. In fact, the braces contain the
pieces of the codes that will be run when a shake on the device is detected. Now, we would like you
to type in the following NSLog() statement below that line:


                                                                                                     26
                    NSLog(@"Shaking Detected");
                             NSLog(@"Shaking Detected");



In iPhone simulator, to emulate the shake gesture, you can select
Hardware -> Shake Gesture




Finally, you can see the following result in the console:




5.3 Variable and Function Declarations
We now define two integer variables score and timeElapsed for keeping the two values. We also
define a function, initializeData, to initialize their values. Both declarations should be done in
the .h file.


Variable declarations should be done inside the braces. Put
   int score;   int score;
                float
   float timeElapsed; timeElapsed;
below the IBOutlet declarations.


Function declarations should be done after the braces but before the @end statement. Put
   - (void)initializeData;
                - (void)initializeData;
anywhere between ‘}’ and @end.




                                                                                                27
5.4 Function Implementation
We proceed to implement initializeData function and also add in the piece of codes that will be
run when shake is detected (refer back to Section 5.1) in the .m file. In the .m file, put

     - (void)initializeData {
                  - (void)initializeData {
         score = 0; score = 0;
           timeElapsed = 0.0f;
                       timeElapsed = 0.0f;
     }                  }


anywhere between @implementation and @end. Of course, do not put it in the middle of any other
function. You can put it just below @implementation for simplicity.


Add in the piece of codes that will be run when the facebook button pressed is detected as follows.
Put the codes after the statement NSLog(@"facebook button pressed");

 score = score + 1; - 1;
       score = score
 timeElapsed = timeElapsed + 1; + 1;
       timeElapsed = timeElapsed


       // write the new on scoreLabel and timeLabel, respectively
 // write the new resultresult on scoreLabel and timeLabel, respectively
 scoreLabel.text = [NSString stringWithFormat:@"%d", score];
       scoreLabel.text = [NSString stringWithFormat:@"%d", score];
 timeLabel.text = [NSString stringWithFormat:@"%.01f", timeElapsed];
       timeLabel.text = [NSString stringWithFormat:@"%.01f", timeElapsed];




5.5 Calling initializeData
Note that we have not specified when to call intializeData yet. To indicate that this method
should be called after loading the view, put the following statement inside the method -
(void)viewDidLoad.


         [self initializeData];
                             [self initializeData];


Note that to make the code effective for execution, you need to uncomment the block for the
viewDidLoad method by removing “/*” and “*/” preceding and following the block, respectively.
That is, the final result will look like:




                                                                                                28
      // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
         // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
      - (void)viewDidLoad {
         - (void)viewDidLoad {
             [super viewDidLoad];
              [super viewDidLoad];
             [self initializeData];
              [self initializeData];
      }
         }


5.6 Run and Debug
After you have made all the changes, save the files and try to run your application. If there is error
in your program, you should notice a “failed” message on the right bottom side of your window.
More details on the errors will be shown when you click on the message. If you can successfully
build your application, you can press the facebook button on the screen to verify whether your
implementation is correct.




5.7 Simple Exercise
In an iPhone application, shaking is generally used as a gesture to reset all the things to their initial
stage. Here, as a practice, we would like you to implement the following function yourself.
Specifically, when you shake the device, the “score” and “time Elapsed” will be reset to zero.


If you cannot finish this part, and you would like to have a look on the result, you can download the
project zip file (Part5_VolcanoRockEscaping_1st_finish.zip) from our website.




                                                                                                         29

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:8
posted:12/9/2011
language:
pages:29