Pages

Minggu, 05 Agustus 2012

Create your own Apple iPhone Clock App


Takeaway: Continuing his basic iOS development tutorial, Todd Moore shows us how to create a simple iPhone Clock App.
In this post, we will make an iPhone Clock App which displays the current time on the screen. This is a continuation from our first Hello World App. Open up the previous Hello project and I’ll show you how to get programmatic access to the label so that the text can be modified within our ViewController class. In order to do this you will need to connect the label in interface builder to a property of the ViewController class.

Automatically sign up for TechRepublic's App Builder newsletter!

Say goodbye

Open ViewControler.xib and use the toolbar to show the assistant editor. (Figure A)

Figure A

The secondary editor is displayed next to the ViewController interface and should automatically open the header file for the ViewController class.
Hold down the control key and then click and drag from the label to inside the view controller header file as shown in Figure B.

Figure B

Once the arrow reaches inside the interface definition you can let go to receive an Outlet connection popup. Set the name of the control to “label” and keep everything else the same as shown Figure C.

Figure C

Xcode will automatically add a property definition for you inside of the header file and also stub out an implementation in the source file. Open up the ViewController.m source file and verify that you can manipulate the label by changing its text to “Bye” in the viewDidLoad method. (Figure D)

Figure D

Run the app (Figure E) and it should now say Bye instead of Hello.

Figure D

Start the clock

Now let’s do something a little more interesting and display the current system time. Add the following code (Figure E) into the source file to create an updateLabel method:

Figure E

This method will allocate an NSDateFormatter object with the date format of “hh:mm:ss” and then use that with the current date to set the label. The updateTime method is then called again using performSelector with a delay of one second. This makes sure the label keeps getting updated and doesn’t just get set one time.
The last step (Figure F) is to call updateTime from the viewDidLoad method:

Figure F

Build and run and you should now see (Figure G) a full screen clock being updated every second.

Figure G

Your new clock app is a lot easier to read than the time contained in the status bar along the top. In my next tutorial, I’ll show you how to take this code and turn it into a stopwatch app.