Building a Simple Stopwatch App in Swift: A Beginner’s Tutorial
Want to build your first iOS app? Follow this beginner-friendly tutorial to create a functional stopwatch app using Swift and UIKit. Perfect for learning basic iOS development concepts.
Introduction
A stopwatch app is an excellent first project for learning iOS development. It covers fundamental concepts like:
- UI design with UIKit
- Timer implementation
- Basic Swift programming
- User interaction handling
Prerequisites
Before starting this tutorial, make sure you have:
- Xcode installed
- Basic understanding of Swift syntax
- iOS development environment set up
Project Setup
- Create a new Xcode project
- Choose Single View Application
- Set language to Swift
- Name it “SimpleStopwatch”
Building the User Interface
Let’s create a clean, functional interface:
class ViewController: UIViewController {
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var startStopButton: UIButton!
@IBOutlet weak var resetButton: UIButton!
// Timer properties
var timer: Timer?
var elapsedTime: TimeInterval = 0
var isRunning = false
}
Timer Implementation
Here’s how we implement the core stopwatch functionality:
extension ViewController {
@objc func updateTimer() {
elapsedTime += 0.1
timeLabel.text = String(format: "%.1f", elapsedTime)
}
@IBAction func startStopTapped(_ sender: UIButton) {
if isRunning {
stopTimer()
} else {
startTimer()
}
isRunning = !isRunning
startStopButton.setTitle(isRunning ? "Stop" : "Start", for: .normal)
}
}
Adding Reset Functionality
@IBAction func resetTapped(_ sender: UIButton) {
stopTimer()
elapsedTime = 0
timeLabel.text = "0.0"
isRunning = false
startStopButton.setTitle("Start", for: .normal)
}
Best Practices
- Memory Management
- Invalidate timer when view disappears
- Clean up resources properly
- User Interface
- Use clear, readable fonts
- Implement proper constraints
- Add visual feedback
- Code Organization
- Separate concerns
- Use meaningful variable names
- Add proper comments
Common Issues and Solutions
Timer Accuracy
To improve timer accuracy:
timer = Timer(timeInterval: 0.1,
target: self,
selector: #selector(updateTimer),
userInfo: nil,
repeats: true)
RunLoop.current.add(timer!, forMode: .common)
State Management
Properly handle app state changes:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopTimer()
}
Testing
Test your app thoroughly:
- Start/Stop functionality
- Reset button
- Timer accuracy
- State preservation
- Memory usage
Next Steps
Consider adding these enhancements:
- Lap times
- Different time formats
- Background running
- Custom themes
- Sound effects
Resources
This tutorial is part of our iOS Development series. Check out our other Swift tutorials for more learning resources.