Build a Stopwatch in Just 3 Steps using SwiftUI
SwiftUI provide us lot of facilities to code user interfaces. In this article we are going to use this framework to build a fully functional stopwatch component in just 3 simple steps.
This is going to be the final result:
Let’s start coding! 🧑🏻💻📲
1. Handle the data needed
First, create the main view for this exercise. This is called
A stopwatch provides us several time units. In our case: hours, minutes and seconds. But we are going to do this as simple as posible. In this way, all these data can be summarized in a single property:
- Progress time can be handle and stored as a
Intwhich represents the amount of seconds since the stopwatch is running.
- We are using
@Statewrapper to get a shared storage managed by SwiftUI. In other words, if data changes, interface also does it.
- That’s a key point on SwiftUI. If you are not familiar with Data Flow in SwiftUI, I encourage you to read this article.
We can get the data time (hh:mm:ss format) from the previous variable using some calculations. To do this we will use computed properties as follow:
Lastly, we just need one more thing: a timer. This updates our
progressTime variable each second. Doing this, we emulate the stopwatch’s behaviour:
2. Data display
We already have all the information needed to display the time as a stopwatch does. In fact, we can use the view
Text and we’d have finished:
Nevertheless result is pretty unaesthetic:
Let’s build then a cleaner solution for this component. In this way, create a new view which represents each time unit on the stopwatch.
This will be called
- It accepts
timeUnitas parameter which is an
Intfrom 1 to 59. We use this to represent any time unit: hours, minutes and seconds.
- First nine digits are just one number: 1, 2, 3… But stopwatches use a two-digits format. This is: 01, 02, 03… For this reason we create the
timeUnitStrcomputed property for a proper representation.
- We use a
Textfor each digit with a fix frame. Doing this, we avoid changing the position of other components when time unit is updated.
Also note that
substring(index:) is a
String extension method:
3. Put all together
Back to the main view, we already have all data and UI components to build our stopwatch. Body view will contain the following:
- Use a
HStackto separate the components horizontally. Moreover when the view appears, timer starts to run. We do this in the
We are done! Preview the
StopwatchView to have something like:
At this point, we have an excellent component that can be easily included in your project to customize it as you want.
In my case, I’m going to add a button to start and stop the count and another to reset it. Moreover, I will follow the project style. Result is the following:
You can find the full code on my repository.