
Let's take our existing Clock App we created during our previous tutorials and turn it into a stopwatch. It will look similar to the standard iPhone Clock implementation.
Open the ViewController.xib file and move rgw label closer to the top to make a little room for a Start/Stop button at the bottom. Now drag a new button over, change the text to "START", and size it so it is about the width of the label. Switch to the Sizing inspector and change the Autosizing to stick to the bottom edge of the view. The button and Autosizing should look like Figure A.Figure A
Figure B
Figure C
Figure D
Figure E
Figure F
I'll explain this method in more detail as it has a few calculations that might look puzzling at first. The code checks if the timer is running and if not then it returns immediately. This will prevent the performSelector method from being called which will stop the timer and the app will be idle until the timer is started again. The time elapsed is calculated by taking the difference between the current time and the start. This represents a floating point value in seconds.
The code then extracts out the total minutes, seconds, and fraction of seconds as integer values. This makes it easier to format a string for display. The minutes are calculated by dividing by 60 and then the total minutes are subtracted from the elapsed variable. This leaves the total seconds remaining which are also subtracted leaving just a fraction of seconds. This is multiplied by 10 so that the final digit will range from 0 to 9. These values are then formatted into a string and the label updated. The performSelector was modified to call every 0.1 seconds so that fractions of a second are displayed.
Build and run the app and you will now have a working stop watch! (Figure G)Figure G
Also read:
- Create a Hello World iPhone app (Part 2 of Todd's tutorial)
- Create your own Apple iPhone Clock App (Part 2 of Todd's tutorial)
- ARC simplifies iOS memory management
Full Bio
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.







