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.
Say goodbyeOpen ViewControler.xib and use the toolbar to show the assistant editor. (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.
Start the clockNow 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:
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:
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.