tai lieu lap trinh tren iphone

Upload: marusathemitc

Post on 06-Apr-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    1/48

    Bi 1: Gii thiu cc cng c lp trnh iPhone

    Theo kinh nghim ca ti th nhng ngi qu quen vi h iu hnh windows v lm victrn nn windows th rt kh m thay i thi quen s dng mt h iu hnh khc. Tuynhin, cng theo kinh nghim ca ti th ch cn b mt thi gian ngn chu kh lm quen vi ci

    mi th t hn s thy c nhiu iu th v m bn windows khng c. Ly mt v d in hnhnh khi bn chuyn t windows sang MAC OS bn s thy MAC chng c g hay ho c, khdng, giao din th ko c bng by nh windows 7, khi cn ng dng cho MAC th tm l licng chng ra, m c ra th cng kh tm c bn crack.Tt nhin l cng phi tu vo tnh cht cng vic m ngi ta nn chn h iu hnh no choph hp. y, cng vic ca chng ta l lp trnh ng dng trn iPhone nn MAC OS l mttrong s cc yu t m bn phi c. Ngoi ra, lp trnh c ng dng iPhone bn cn c 1 biPhone SDK do Apple cung cp, phin bn mi nht hin nay l 3.1.2 v mt b XCode cngphin bn dng coding v ko th giao din.

    iPhone SDK v XCode th c th d dng download ti trang web ca Apple cn MAC OS th

    tt nht l mua a dnh cho PC. Vic ci t MAC OS trn PC thc s khng phi d dng chtno v theo nh kinh nghim ci MAC ca ti th mi my PC c mt dng MAC OS ring chack c th lm vic c trn nn phn cng tng ng. Do m khi bn chn mua aMAC nn ch n cu hnh phn cng ca my. Chng hn nh card m thanh l do realteksn xut hay hng khc, card ho VGA hay Nvidia, card mng,... Ch cn bn chn cu hnhphn cng lch mt cht trong qu trnh ci t th coi nh cng cc.

    Ngn ng lp trnh ng dng trn iPhone l Objective-C. y l mt ngn ng lp trnhhng i tng. Tc gi pht trin k tha trnh bin dch C v to nn trnh bin dch micho Objective-C. V vy m trnh bin dch Objective-C c th bin dch c c ngn ngC/C++. Trong lp trnh iPhone bn c th vit c 3 ngn ng trong cng mt application.

    V XCode th phi ni l qu tuyt vi khi lp trnh trn iPhone do n h tr rt mnh choiPhone. Bn s ko cn phi quan tm v cc i tng UI na. V Xcode qun l cc i tngUI rt cht ch. Chng hn nh thay v bn khai bo i tng UIButton th bn ch vic ko itng button vo View v nh x n ti bin UIButton trong m ngun n s t ng khi tokhi load ln...

    C l ch mt vi li cng kh m din t ht c ci hay ca XCode. Thay vo bn ch cth tri nghim v cm nhn.

    Bi tip theo chng ta s hc v cc i tng UI trong lp trnh ng dng trn iPhone v cu

    trc ca chng.

    (Xin lu , cc ti liu v iPhone hon ton c copy t trang iCodeblog.com V mt vi ngihiu nhm ngh mnh copy bn quyn. Nn edit thm ch ny mi ngi bit r. Ngoi ra,theo mnh ngh th thy ti liu hay hoc c kin thc g mnh cho l b ch th mnh s post lnv c gng nhn rng ra mi ngi d tm kim hn khi s dng google search)

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    2/48

    Bi 2: UITableView Hello world

    Friday, January 22, 2010 1:57:00 PM

    iPhone

    Trong bi ny s hng dn cho cc bn cch to mt ng dng "Hello world" s dngUITableView.Mc tiu ca bi hc:- Create a New Navigation-Based Application- Learn About the Default Files- Update the UITableView Cells to Display Hello World Text

    Creating a New Navigation-Based Application

    Start a new iPhone OS Project

    Click Xcode > New Project and a window should pop up like this:

    Make sure Application is selected underiPhone OS and then select Navigation-BasedApplication. ClickChoose It will ask you to name your project. Type in Hello World andlets get started.

    Learn About the Default Files

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    3/48

    What is all this stuff?There are quite a few files that get added to your project. At first glance, this looks kind ofintimidating. Dont worry, we only need to edit one of them. Here is a quick explanation of thedifferent files. You dont have to read this part but having this many files is what confused methe most when I started developing for the iPhone.

    1. CoreGraphics.framework, Foundation.framwork, UIKit.framework You guessedit, this is a set of library functions provided by Apple that we use in our application. Weuse these as includes similar to any other language that includes library functions.

    2. HelloWorld.app This is your app that gets installed on the iPhone. We dont reallyneed to worry about this right now

    3. Hello_World_Prefix.pch This is another include file that gets compiled separatelyfrom your other files so you dont need to include it on each file. It contains some code toinclude the data inside the frameworks.

    4. Hello_WorldAppDelegate.h This is a header file that contains all of our definitions forvariables that we will be using. Its very similar to a header file in C or C++;

    5. Hello_WorldAppDelegate.m All of the magic starts here. Consider this file ourstarting point for execution. The main.m file invokes this object.6. Info.plist This contains various meta information about your program. You wont

    really need to edit this until you are ready to start testing on the iPhone7. main.m Like most programming language, this file contains our main function. This is

    where execution begins. The main function basically instantiates our object and starts theprogram. You shouldnt need to edit this file.

    8. MainWindow.xib This contains the visual information of our main window. If youdouble click on it, it will open in a program called Interface Builder. We will get to thisa little later. Just on thing to note is this file does not contain any code.

    9. RootViewController.h, RootViewController.m - These are files for a view controllerthat gets added to our main window. Basically, Apple has already created a simpleinterface when you clicked on Navigation-Based Application. Since most navigation-based applications use a Table View, Apple has provided it for us to use.

    10.RootViewController.xib This is a view that Apple has provided that emulates a table.It has rows and columns. We will be displaying our Hello World text inside one ofthese rows

    Now, all of these files together create a basic program. Go ahead and click on the Build and Gobutton at the top of Xcode. Make sure the drop-down on the top left says Simulator | Debug,this tells Xcode that we are testing on the iPhone simulator.

    You will see the iPhone simulator start and your program will launch. Its not very interesting atthe moment. All it shows is the Table View that Apple has added for us. So what we are going todo is add a row to this table view.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    4/48

    Update the UITableView Cells to Display Hello WorldText

    Lets write some codeStart by opening RootViewController.m. This is the view controller that Apple added to ourmain view. All of the functions you see already created in here are functions that have beenoverridden from the Table View super class. Since we are editing a table, all of these functionswill be related to editing a table. So find the function called numberOfRowsInSection.

    This function tells the application how many rows are in our table. Currently, it returns 0. Letschange that to return 1. This will tell the application that we want 1 row in our table. Now godown to the function called cellForRowAtIndexPath. This function gets called once for everyrow. This is where we define what content to display in a given row. In this case we want therow to be a string that says Hello World.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    5/48

    What this function is doing is creating a new cell object and returning it. The code between thei(cell==null) block checks to see if we have created a cell before, if not build a new cell,otherwise use the one we created before. This helps in performance so we dont need to buildnew cells each time we visit this function. So right before the // Set up the cell comment add thefollowing code:[cell setText:@"Hello World"];

    We are basically calling the setText method of the cell object and pass in the string HelloWorld. As you should know from reading Apples Objective-C overview, strings begin with an@ symbol.Thats it! Click the Build and Gobutton again to launch the iPhone simulator. You should nowsee a screen like this:

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    6/48

    You can now use this code as a base for creating a Navigation Based application. In a later

    tutorial, I will detail how to populate this table view with an array of strings to create navigationfor a simple program. If you get lost at any time, you can download the sample code for thisprogram here hello-world. I hope you enjoyed the tutorial and if you have any questions, feelfree to leave them in the comments. Happy Xcoding!

    Bi 3: Beginner Interface Builder Hello World

    Friday, January 22, 2010 2:05:21 PM

    iPhone

    Bi ny hng dn cch xy dng mt ng dng "Hello world" bng cch ko th trong interfacebuilder ca XCode.Trong bi ny cc bn s c hc v:- Create a New View Based Project (To mt project vi i tng c khi to ban u lUIView)- Opening the iPhone Simulator

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    7/48

    - Adding UI Elements to your home screen- Executing the code (Cch thc thi chng trnh)

    In my last tutorial UITableView Hello World I said that there are many ways to write a Hello

    World tutorial for the iPhone. Here is one using Interface Builder. Last time, I demonstrated asimple way to populate one cell in a UITableView with some text. Todays tutorial is evensimpler. I will show you how to work with Interface Builder to create a simple layout for youapplication. In fact, you wont write any code at all! In my next tutorial, I will detail how tointerface with your UI components in code.

    In this tutorial you will learn:

    y Create a New View Based Projecty Opening the iPhone Simulatory Adding UI Elements to your home screeny

    Executing the code

    Create a New View Based Project

    Lets start by opening up XCode and Creating a new View-Based Application. Do this byclicking onFile > New Project. Make sure that Application is highlighted underiPhone OS and selectView-Based Application.Name this project HelloWorldViews.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    8/48

    So at this point, Apple has added some default files to get us started. They have added the mainwindow for us to edit along with the code to launch the window. Now in iPhone terms, eachwindow is called a View. Since you can only see one view at a time, you will need to create anew view for each screen in your application. In this tutorial, we will be sticking to editing theview Apple has provided us. In later tutorials, I will go into how to add new views and transition

    between them. Go ahead and clickBuild and Go.

    Opening the iPhone Simulator

    The program should compile and launch the iPhone Simululator. Your screen should looksomething like this.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    9/48

    Advertisement

    //

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    10/48

    src="http://ad4.netshelter.net/adj/ns.icodeblog/general;kw=;tile=4;sz=300x250,336x280;ord=' +ord + '?">'); //]]>

    Not very interesting right? Excuse my crappy screenshot. So lets add some UI components toour view to make it more interesting. To do this we will be editing

    HelloWorldViewsViewController.xib . A file with the .xib extension is known as a nib file.These files open with Interface Builder and are where you define the look and feel of yourapplication. Apple is nice enough to have provided us with one.

    Adding UI Elements to You Home Screen

    Once you open Interface Builder, you should see a few different windows You should see ablank window that has the same dimentions as the iPhone that says View up in the top. If notclick the View icon in the smaller box. This is the main window we will be editing.

    To the right, you should see a tool box that contains many different UI components. Most ofthem should look familiar if you have ever used an iPhone application. So lets add a few ofthem to our view. Just click on the ones you want and drag them on to your view. Make sureyou at least use a Label. For this tutorial, I have used a Label, Search Bar, and a Tab Bar.Notice when you drag the search bar and tab bar onto the view, they size correctly to the screen.Also, if you move the items around, you will see blue lines that guide you. These are in place to

    help you line up components and center them.After you have added the label, click on it. Now lets open the Attributes Inspector to changethe text of the label. To do this clickTools > Attributes Inspector. At the top of the AttributesInspector you should see a box labeled Text. If you dont click on the label again to select it. Putwhatever you would like the label to say in that box. I put Hello World. You can update otherproperties of the label including color and font using the Attributes Inspector. You may need toresize the Label to accommodate your new text. To do this click on the label and you will seelittle boxes around it that you can drag to resize the text area.

    After you are done, your interface should look something like this:

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    11/48

    Now press Apple-S to save this file. We are done with Interface Builder so you can close it. Yourapplication should now be ready to execute.

    Executing the Code

    Go ahead and clickBuild and Go again to launch the iPhone Simulator. Your screens shouldlook something like this:

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    12/48

    There you have it! A simple iPhone application without writing a line of code. If you click in thesearch box, the iPhone will automatically pull up the keyboard. Thank you for reading thistutorial and I hope that you have learned something. In my next tutorial, I will show you how touse code to interface with our UI components. If you have any questions, feel free to leave themin the comments. Happy iCoding!

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    13/48

    Bi 4: Connecting Code to An Interface Builder View

    Friday, January 22, 2010 2:19:12 PM

    iPhone

    Finally, we get to write some real code! In this tutorial, I will show you how to create aninterface using Interface Builder and connect it to your code. We will be creating a UITextField,UILabel, and a Button. Now, dont be intimidated that this tutorial is so long. I have really wentinto detail explaining everything as I go. You could easily scan over it and get the gist of it.Heres how the application will work:

    1. The user will tap inside a text box which brings up the iPhones keyboard2. The user will type their name using the keyboard

    3. The user will press a button4. The label will update with a greeting containing that users name (ex. Hello Brandon!)5. If the user fails to enter in text, the label will say something like Please Enter Your

    Name

    Prerequisites: This tutorial assumes that you have completed the following tutorials

    y Hello World Tutorial Using UITableViewy Beginner Interface Builder

    In this tutorial you will learn:

    y Create a new View-Based applicationy Create a simple user interfacey Write code to connect to an interfacey Connect the interface to the codey Update the interface based on user interaction

    Like the last tutorial I wrote, we are going to need only one view. So we will just use ApplesView-Based Application template. So clickFile -> New Project. Select View-BasedApplication and name it ViewBased (You can name it whatever you want).

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    14/48

    So like last time, Apple has provided us with most of the code needed to get this app up andrunning. You can clickBuild and Go to launch the simulator, but all you will see is blankness.

    Lets get started by double clicking on ViewBasedViewController.xib. This is a nib file thatopens with Interface Builder. It contains information regarding the layout and controls of ourview. Once you do this, Interface Builder should open up.

    It will look something like the screenshot below.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    15/48

    A few notes about interface builder

    Library The right-most window contains all of your controls that you can add to your view.For this tutorial we will be using a TextField, Label, and Button.

    The next window to the left of that contains objects that we will connect our interface to. Viewrepresents the view of this nib file (basically the interface). Files Owner is the object that linksthe interface to the code.

    View - This is your user interface for your iPhone application. This window is where you willdrop controls from the right-most window.

    Attributes This is where we will set the styling properties of our controls

    Add a Text Field

    The first thing you want to do is drag a Text Field from the library box on to yourviewwindow. You will see some blue lines to guide you. These are in place to help line up controls aswell as center them.

    Once you have added the Text Field to the View, move it around until its in a position that youare happy with. Next, stretch each side of the text box so that it spans accross almost the entireview area. (The blue lines on the right and left will let you know when to stop.)

    Now we are going to set some of the attributes of the Text Field. If the Attributes Inspectordoesnt appear, click on the Text Field and then clickTools -> Attributes Inspector.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    16/48

    y In the Placeholder field type in Name. This is the default text that appears in the TextField before a user types anything.

    y ForCapitalize select Words This tells XCode that we want to capitalize each wordy ForReturn Key Select Done. This makes the return key on the keyboard say Done

    rather than return.y

    Also, make sure Clear When Edit Begins is checked

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    17/48

    Add a Label

    Drag a Label from the Library onto yourview. Similarly, stretch it the length of yourview andplace it where you would like. Lets change the default text of the label. If the AttributesInspector doesnt appear, click on the Label and then clickTools -> Attributes Inspector. In

    the Text field type in Enter your name above (or below depending on where you chose to putthe label in relation to the Text Field.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    18/48

    Add a Button

    Now drag a Button from the library onto yourview. Stretch it and position it however youwould like. Now we need to add some text to the Button. Click on the button and then clickTools -> Attributes Inspector. In the Title field, type Display.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    19/48

    We are now done creating our interface. It should look something like this:

    Advertisement

    //

    Lets return to our code Close Interface Builder and go back to Xcode.

    The files that link an interface to some code are called View Controllers. Lets open upViewBasedViewController.h. This is the file where we will declare all of our interfacevariables. Add the following code to you ViewBasedViewController.h.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    20/48

    Interface Builder uses IBOutlets and IBActions to connect to the code. Here is a briefexplanation of each line of code.

    y IBOutlet UITextField *textName creates an outlet to connect to the text field wecreated in interface builder. We use this variable to get information from the text field.

    y IBOutlet UILabel *lblHello An outlet that connects our label on our interface to thecode. This variable is used to set the value of the label.

    Now that we have declared these variables, we need to make them properties. This allows us toset certain attributes that are associated with the variables. Retain tells the compiler that we willhandle the memory management of this object (dont forget to release it when you are done).Otherwise it will get cleaned after being instantiated.

    There is one other thing here.

    - (IBAction) updateText:(id) sender;

    This is the function that will get called when the user presses the button that was created inInterface Builder. We are simply declaring it here in the header file. We will implement thisfunction a little later in the tutorial. Now, we need to connect the interface to the code. Doubleclick on ViewBasedViewController.xib again to open up Interface Builder.

    1. Connect the View1. Click anywhere on the background of your view (anywhere that is not the Text

    Field, Label, or Button). Now clickTools -> Connections Inspector.Next toNew Referencing Outlet, you will see a circle. Click in that circle and drag theblue line to the Files Owner object and release it. The word view should pop up.Click on it. You have now connected the view to your proxy object. You shouldnow see:

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    21/48

    2.

    2. Connect the Text Field1. Click on the Text Field in yourView window to select it. Then clickTools ->Connections Inspector. You will now see a circle next to New ReferencingOutlet. Click in that circle and drag it over to the Files Owner object. Amessage will pop up with txtName. Click on txtName and the connection ismade. You should now see:

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    22/48

    2.

    3. Connect the Label1. Click on the Label in yourView window to select it. Then clickTools ->Connections Inspector. You will now see a circle next to New ReferencingOutlet. Click in that circle and drag it over to the Files Owner object. Amessage will pop up with lblHello. Click on lblHello and the connection is made.You should now see:

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    23/48

    2.

    4. Connect the Button1. Click on the Button in yourView window to select it. Then clickTools ->Connections Inspector. You will now see a circle next to Touch Up Inside. Thisis the trigger that gets called when a user presses the button. Click in that circleand drag it over to the Files Owner object. A message will pop up withupdateText. Click on updateText and the connection is made. You should nowsee:

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    24/48

    2.

    Now all of the connections should be set up. Go ahead and close Interface Builder. We are doneusing it.

    Open up the file ViewBasedViewController.m . This is the file where we will implement theupdateText function. Add the following code

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    25/48

    This code is pretty straight forward and easy to follow. I will explain it line-by-line:

    @synthesize txtName,lblHello;

    Most of the time when creating (private) variables, you need to specify what are called getterand setter methods. Theses functions get the value of a variable and set the value of a variable.What synthesize does is creates these methods for you under the hood. Pretty handy

    Next we will implement ourupdateText method. I started by creating a temporary string. This isthe string that we will insert into the text of the label.

    The next line checks to see if the user has entered any text int the Text Field. txtName.textreturns an NSString. We are simply calling the length method on a string. If the length is 0, thenobviously the user has not entered any text. If this is the case, we set the temporary string toPlease enter your name: instructing the user to enter in their name.

    If the user has entered in some text, a new string is allocated. The initWithFormat method issimilar to printfin C. So, I used the string Hello %@!. The %@ in the string means we willbe substituting it for a string. To get the value of the Text Field we again use the txtName.textproperty.

    Finally, the value of the Label is set by calling lblHello.text. This calls the text property of labeland sets the text to our temporary string variable.

    The last line ; releases the temporary text field from memory. This is necessary to write anefficient iPhone application. If you want to know why a lot of iPhone apps crash, its because thedevelopers dont follow through with this step.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    26/48

    Thats it! ClickBuild and Go. The application should launch in the iPhone Simulator. Whenyou click inside the Text Field it should bring up the iPhones keyboard (you can also type withyour keyboard). Enter in your name and click Display. Here are a few screens of what yourapp should look like.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    27/48

    User Clicks Display without typing in their name

    User types in their name and clicks Display

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    28/48

    Well, that concludes this tutorial. I hope that I was able to help you out on your road to iPhoneglory. If you get lost at any point you can download the code to this tutorial hereViewBasedSampleCode. As always, if you have any questions or comments, be sure to leavethem in the comments section of this page. Happy iCoding!

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    29/48

    Bi 5: Transitioning Between Views

    Monday, January 25, 2010 3:40:15 PM

    iPhone

    Phn ny s hng dn cho cc bn cch chuyn qua li gia cc UIView vi nhau. C 2 cch chuyn qua li gia cc View: 1. Nu s dng NavigationBar th n gin l push view cnchuyn vo NavigationBar v thc t NavigationBar l mt stack cha cc View. i tngView c hin th l i tng trn nh stack. Ngc li quay li View trc th chcn pop View trn cng ra. Cch lm chi tit nh th no th bi ny s tng bc hng dn cth cho cc bn. 2. Nu khng s dng NavigationBar v bn mun chuyn t mt View hin tisang mt View khc th bn thn i tng View cung cp cho chng ta hm addSubView.Nu bn ang ng mt i tng k tha t UIView th s dng lnh [selfaddSubView:] Di y l nguyn bn tutorial trong tranghttp://www.icodeblog.com

    This tutorial will focus on transitioning from one view to another. We will be utilizing ApplesUINavigationController. I will be using the code from the Hello World tutorial that Ipreviously wrote. So if you have not completed it yet, go ahead and do it and come back to thispage. (Its quick I promise). You can view it here.

    In this tutorial you will learn:

    y Add A New Viewy Add A View Controllery Set Up The Transition To The Viewy Connect The View To The Codey Add A Back Button

    The first thing we are going to do is change our Hello World text to say something that soundsmore like navigation. Go ahead and open RootViewController.m. Location thecellForRowAtIndexPath method (its the one that you edited to display Hello World in thetable cell.

    Change the line: [cell setText:@"Hello World"] ; to [cell setText:@"Next View"];

    Add A New View

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    30/48

    We will now add the view that we will be transitioning to. Click on RootViewController.xiband this should open up Interface Builder. We dont actually need to edit this file. Once insideInterface Builder click on File -> New and select View.

    It will add a blankView to your project. For now, we will keep it simple. Go ahead and drag anew Label on to the View. Double click on the label and change the text to whatever you want. I

    set mine to View 2 (I know, not very imaginative).

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    31/48

    Lets save the view. ClickFile -> Save. Call it View2. Make sure that you save it inside yourHello World projects directory. It may want to save it somewhere else by default.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    32/48

    Next, you will see a screen asking you if you want to add the View to your project. Check thebox next to Hello World and clickAdd.

    Close Interface Builder. Drag the View2.xib file into the Resources folder, if it didnt appearthere by default (this will help maintain organization).

    Add A View Controller

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    33/48

    Now we need to create a ViewController class. This class will be used to connect the view thatwe just created to our code. Inside ofXcode clickFile -> New File Select UIViewControllersubclass and clickNext.

    Name it View2ViewController and make sure Also create View2ViewController.h ischecked. ClickFinish to continue. This will add the new ViewController to your project.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    34/48

    For organization sake, drag yourView2ViewController.h and .m files into the Classes folder ifthey didnt appear there to begin with.

    Set Up The Transition To The New View

    Open up RootViewController.h and add the following code:

    This code should be pretty self explanatory, but I will explain it anyway. The import statement

    #import View2ViewController.h gets the header file of the ViewController that we createdand allows us to create new instances of it.

    Next, we declare a variable called view2ViewController which is of the typeView2ViewController. One thing that I want to point out is the first part starts with a capitolV which is the type of object that we are declaring. The second part starts with a lower casev. This is our variable name that we will use to reference ourViewController object. Finally,we make our variable a property to set additional information.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    35/48

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    36/48

    View2ViewController class object with the view so click on the Files Owner object and thenclickTools -> Identity Inspector.

    Click the dropdown next to class and select View2ViewController.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    37/48

    Next click anywhere on your view to select it. ClickTools -> Connections Inspector. Click inthe circle next to New Referencing Outlet, drag it to the Files Owner object and release it. Theword view will popup. Go ahead and click on it.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    38/48

    Close Interface Builder. You can now clickBuild and Go. When you click on the words NextView, you will see the screen transition to your new view. There is still one thing missing.There is no back button in the NavigationController at the top. Apple actually adds this for us,but we need to set a title on our main view.

    Adding The Back Button

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    39/48

    Close the iPhone Simulator and open RootViewController.m. In the viewDidLoad method(gets called when the view is first loaded) add the following code.

    Since RootViewController extends Apples class UITableViewController, it comes with a titleproperty. You can set this to anything you want. I have set it to the string Hello. Now clickBuild and Go and you are done. Here are a few screenshots.

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    40/48

    When you click on Next View it should transition to:

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    41/48

    Notice the back button at the top with the text Hello. If you press it, your view will be poppedfrom the NavigationController stack and the previous view will be shown. If you have anyproblems/questions/comments post them in the comments. Im pretty good about answeringthem as it emails me when you do so and I receive them on my iPhone. If you have anyproblems, you can download the source code here Hello World Views Source. Happy iCoding!

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    42/48

    Bn s thao tc vi b cng c Xcode thc hin mi cng vic trong qu trnh pht trin ccng dng ca mnh.To new iPhone OS ProjectVo Xcode>New Project mt ca s mi s xut hin nh hnh di

    Bn phi chn Application bn di iPhone OS v chn Navigation-Based Application. BmChoose v bn s c yu cu t tn cho project. G vo HelloWorld v ta cng bt u.Tm hiu v nhng files mc nhBn c t hi nhng file g m nhiu vy?C kh nhiu file c t ng thm vo project ca bn. Ln u mi nhn, mnh c cm gicnh l ang b e da. ng qu lo lng, chng ta ch cn chnh sa mt file trong s . Sauy mnh s gii thch s qua v cc file khc. Bn c th b qua khng cn c phn ny, tuynhin ln u tin khi thy nhiu file nh vy khi lp trnh iPhone, mnh cm thy kh bi ri.1. CoreGraphics.framework, Foundation.framework, UIKit.framework- Chc bn on c,y l mt tp hp cc library functions cung cp sn bi Apple m chng ta s s dng trongcc ng dng ca mnh. Chng ta s dng chng ging nh vic include th vin trong cc ngnng lp trnh khc.2. HelloWorld.app y chnh l ng dng ca bn c ci t vo iPhone. Ngay lc ny,chng ta cha tht s cn quan tm n n.3. Hello_World_Prefix.pch y l mt file c include khc, bin dch t nhiu file ring bitgip bn khng cn phi include tng file mt vo trong project. File ny cha mt s on m

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    43/48

    include d liu bn trong frameworks.4. Hello_WorldAppDelegate.h y l file header cha tt c cc nh ngha v bin m ta s sdng. Tng t nh mt file header trong C hay C++.5. Hello_WorldAppDelegate.m Phn ct li ca ng dng nm y. File chnh l im btu ca ng dng. File main.m gi object ny.

    6. Info.plist file ny cha nhiu thng tin(meta information) khc nhau trong chng trnh cabn. Bn s khng cn phi ng chm n file ny cho n khi bn sn sng cho vic test thchng trnh trn iPhone.7. main.m Ging nh hu ht cc ngn ng lp trnh khc, file ny cha hm main. y l khiim ca chng trnh. Hm main v c bn khi to object v khi ng chng trnh. Bnkhng phi chnh sa file ny.8. MainWindow.xib Cha cc thng tin trc quan v ca s mn hnh chnh(main window).Nu bn nhy p ln n, mt chng trnh c tn gi Interface Builder s c c mra.Chng ta s ni n Interface Builder sau. Bn cn nh mt iu, file ny khng cha bt kmt dng m no c.9. RootViewController.h, RootViewController.m Nhng file ny dng cho mt view controller

    c thm sn vo ca s mn hnh chnh(main window). V c bn, Apple to sn mtgiao din n gin ngay khi bn bm vo Navigation-Based Application. V hu ht cc ngdng kiu navigation-based u s dng mt TableView, Apple cung cp sn cho chng ta.10. RootViewController.xib y l mt view m Apple cung cp sn di dng table. N ccc dng v ct. Chng ta s hin th li cho HelloWorld trn mt trong s cc dng ca tableny.Tt c cc file trn tp hp li to nn mt chng trnh c bn. No, bn hy bm vo ntBuild and Go pha trn ca Xcode. Ch ci drop-down pha trn bn tri hin thSimulator|Debug, c ngha l bn bo Xcode rng bn ang test trn thit b gi lpiPhone(iPhone Simulator).Cp nht UITableView Cells hin th li cho HelloWorld.By gi chng ta s code t chtTa bt u bng vic m file RootViewController.m. y l view controller m Apple thmsn vo ca s chnh ca chng trnh. Tt c cc hm m bn thy c to sn y coverridden t lp cha TableView. V chng ta ang chnh sa table nn cc hm ny lin quann thao tc chnh sa table. Tm hm numberOfRowsInSection.Code:

    -(NSInteger)tableView:(UITableView*)tableView

    numberOfRowsInSection:(NSInteger)section{

    return 0;

    }

    Hm ny cho ng dng bit table s cha bao nhiu dng. Hin ti n tr v 0. Chng ta s sali thnh return 1. Ta mun ng dng s hin th 1 dng trn table. By gi, ko xung hmcellForRowAtIndexPath. Hm ny c gi mt ln i vi mi dng. y l ni ta s nhngha nhng g s c hin th ti tng dng. Trong trng hp ny ta mun hin th li choHello World.Code:

    - (UITableViewCell *)tableView:(UITableView *)tableView

    cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    44/48

    static NSString *MyIdentifier = @MyIdentifier;

    UITableViewCell *cell = [tableView

    dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil) {

    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero

    reuseIdentifier:MyIdentifier] autorelease];}

    // Set up the cell

    return cell;

    }

    Nhng g m hm ny ang lm l to ra mt i tng cell v return i tng ny. on mtrong khi if(cell==nil) kim tra xem chng ta to ra mt cell trc cha. Nu cha, tomt cell mi, cn khng th s dng cell to trc . Vic ny gip cho ng dng cperformance tt hn v ta khng phi to ra cell mi mi ln chng trnh gi li hm ny. Bnthm dng code sau vo ngay trc dng ch thch // Set up the cell:Code:

    [cell setText:@Hello World];

    - (UITableViewCell *)tableView:(UITableView *)tableView

    cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *MyIdentifier = @MyIdentifier;

    UITableViewCell *cell = [tableView

    dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil) {

    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero

    reuseIdentifier:MyIdentifier] autorelease];

    }

    [cell setText:@"Hello World"];

    // Set up the cell

    return cell;

    }

    Ta gi phng thc setText ca i tng cell v truyn vo chui Hello World. Bn bit rngtrong Objective-C, chui bt u vi k t @. By gi bm nt Build and Go khi ngiPhone Simulator. Bn s thy mt mn hnh nh di y:

    Lp trnh iphoneIPHONE - SN PHM LM NN CUC CCH MNG TRONG L NH

    VC IN THOI THNG MINHIPhone l g ?-

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    45/48

    IPhone l mt in thoi di ng tch hp v mynghe nhc a phng tin cpht bi Apple.Thit b ny kt hp cc chc nng chnh ca mts tin ch ph binin t trong mt thit b duynht, vi mt g iao din c chia s v hinhpgia chng. Ngoi chc nng chnh ca n nh lmt in thoi di ng,iPhone cn bao gm mynghe nhc, xem video, my nh k thut s, PDA,v

    l mt b truyn thng Internet.Lch s pht trin ca Iphone :-IPhone u tin c cng b bi cu Gim c i u h n h S t e v eJ o b s c a A p p l e v o n g y 09/01 /2007 v ph t hnh vongy 29 /06 /2007. IPhone th h th 5, iPhone 4S, c cng b vongy04/10/2011, v pht hnh vo ngy 14/10/2011, hai ngy sau khi pht hnhiOS 5.0, hiu hnh ca Apple cho cc thit b cm tay .

    iu g to nn s khc bit ca Iphone ?

    1 . M n h n h c m n g r n g-Vi Iphone , mn hnh chnh l in thoi . Mi th c thc hin thngqua mn hnhcm ng 3.5 inch v ngy cng ln hn qua cc phin bn tip theoca IPhone .2 . C m n g a i m

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    46/48

    -Iphone chnh l in thoi thng minh u tin s hu chc nng cm nga im . Ta cth phng to mt trang web , mt bc nh hoc mt tm bn bng cch s dng ccngn tay .3 . S e n s o r s ( B c m b i n )-Cm bin th nht l gia tc k, khi bn quay ngang in thoi , n s t ng thay i

    mnhnh hin th theo ch phong cnh. Tnh nng ny l v cng hu ch xem nh toncnh, video hoc lt qua cc album ca cc bn-Cm bin th hai pht hin nh sng xung quanh v iu chnh sng ca mn hnhphhp tit kim nng lng.-

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    47/48

    Cm bin th ba s v hiu ha mn hnh khi bn hng in thoi v pha khun mtca bn, v vy bn s khng c quay s trong khi ni chuyn trn thitb . 4 . I p h o n e O S P l a t f o r m ( i O S )-IPhone s dng h iu hnh c ngun gc t Mac OS .I.

    Cc lp v nn tng ca iOS1.Tng quan v iOS.iOS (trc y c gi l iPhone OS) l h iu hnh di ng ca Apple. u tin OSchc pht trin cho iPhone, sau ny c m rng h tr cc thit b khcca Apple ,chng hn nh iPad , iPodiOS bao gm h iu hnh v cc cng ngh m bn s dng chy cc ng dngnguyn bn trn cc thit b, chng hn nh iPad, iPhone, v iPod touch. Mc d chias mt thnhtu chung v cc cng ngh c bn vi h iu hnh Mac OS X,

    IOS c thi t k png nhu cu ca mt mi trng di ng, ni m nhu cuca ngi s dng hi khc nhau. Nu trc bn pht trin cc ng dngcho Mac OS X, bn s t m thy nhiu cngngh quen thuc, nhng bn cng stm thy cng ngh ch c trn iOS, chng hn nh giaodin Multi-Touch v h tr giatc.IOS SDK c cha m, thng tin, v cc cng c bn cn pht trin, kim tra, chy,g liv iu chnh cc ng dng cho iOS. Cc cng c ca Xcode cung cp cc chcnng chnh

    sa c bn, bin son, v mi trng g ri cho m ca bn. Xcode cng cung cpim ramt th nghim cc ng dng ca bn trn mt thit b iOS, v iOSSimulator-mt nntng m phng mi trng c bn iOS nhng chy trn my tnhMacintosh a phng ca bn.2.Kin trc ca iOSKin trc iOS l tng t nh kin trc c bn trong Mac OS X. tng caonht (top layer), iOS hot ng nh mt trung gian gia phn cng c bn v cc ngdng xut hin trnmn hnh. Cc ng dng m bn to ra him khi tng tc trc tipvi phn cng c bn. Thayvo , cc ng dng giao tip vi phn cng thng quamt tp hp cc cc giao din h thngcng c xc nh bo v ng dng ca bnt nhng thay i phn cng. S tru tng nylm cho n d dng vit cc ngdng lm vic nht qun trn cc thit b vi cc kh nngh tr phn cng khc nhau.

    Figure 1-1Applications layered on top of iOSNhn ca iOS c da trn nhn ca Mac c bn c tm thy trong h

    iuhnh Mac OS X. Lp trn cng ca nhn ny l cc lp dch v c s dng

  • 8/2/2019 Tai Lieu Lap Trinh Tren iPhone

    48/48