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.
Todd Moore is an app developer, technology host, and published author. His most popular application, White Noise, has been downloaded by millions of sleep-deprived customers. Although his app has received critical acclaim in the press, the biggest compliment came from Jimmy Fallon when he spoofed an Axl Rose edition of it on his "Late Night" show. Todd recently published the book, Tap, Move, Shake (featuring a foreword by Steve Wozniak of Apple, Inc.), which shows how anyone can publish their ideas to the iTunes App Store. He can be found giving tech advice at mobile conferences and on his weekly Tech 411 podcast. Todd resides in the greater Washington D.C. area.