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.
Bring up the assistant editor as you did in the previous article so that an action can be added when the button gets tapped. Draw a connection by holding down the control key while dragging from the button to below the label property and release. This time you need to change the connection type to Action, set the name to “onButton” and change the Type to UIButton. Make sure the popup looks like Figure B before clicking connect.
We need to add a couple more variables to track the start/stop state of the timer and when the timer was started. Modify the header file so that it appears as it does in Figure C. (Notice we needed to add a couple brackets too.)
The app will require the user to tap the start button to get things going. In the viewDidLoad method remove the updateTime call, set the label text to show a timer resting at zero, and set the running variable to false. (Figure D)
In the onButton method modify the contents to start and stop the timer. (Figure E)
Now implement the timer display logic in the updateTime method. This requires a few calculations. Modify the method so that it appears as shown in 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)