Skip to content
DeveloperMemos

Triggering a Timer Function on UIButton Click

iOS, Swift, UIButton, Timer2 min read

In iOS development, it's common to perform specific actions when a button is clicked. One such scenario is triggering a timer function upon clicking a UIButton. This can be useful for implementing features like countdown timers, interval-based tasks, and more. In this article, we will explore how to achieve this functionality using Swift, the programming language for iOS development.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  • Basic knowledge of iOS development with Swift.
  • Xcode installed on your machine.
  • Familiarity with UIButton and Timer concepts.

Setting Up the User Interface

To get started, open Xcode and create a new iOS project or open an existing one. Then, follow these steps to set up the user interface:

  1. Open the Main.storyboard file.
  2. Drag and drop a UIButton from the Object Library onto your view controller.
  3. Customize the button's appearance and position as desired.

Handling Button Click Events

Now that we have our button in place, let's move on to handling its click events. In Swift, you can handle button clicks using the Target-Action pattern. Follow these steps to link the button to a method that will be called when it is clicked:

  1. Open the Assistant Editor by selecting View -> Assistant Editor -> Show Assistant Editor from the Xcode menu.
  2. Ensure that the ViewController.swift file is displayed in the Assistant Editor.
  3. Ctrl-drag from the UIButton in the storyboard to the ViewController class in the Assistant Editor.
  4. In the dialog that appears, set the Connection to "Action" and provide a name for the method. For example, let's name it startTimer(_: ).

The code snippet below shows an example of how the method would be defined in your view controller:

1@IBAction func startTimer(_ sender: UIButton) {
2 // Implement timer functionality here
3}

Implementing the Timer Function

Now that we have our button click event handler in place, let's proceed with implementing the timer function. We'll use the Timer class provided by Swift to achieve this.

In the startTimer(_: ) method we defined earlier, add the following code to create and start the timer:

1@IBAction func startTimer(_ sender: UIButton) {
2 Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
3}
4
5@objc private func timerFired() {
6 // Timer logic goes here, executed every second
7}

In the above code, we're using the scheduledTimer method of the Timer class to schedule a timer that fires every second. The target parameter specifies the object that should receive the timer callback, which in this case is self (the current view controller). The selector parameter refers to the timerFired method that will be called upon each firing of the timer.

Inside the timerFired() method, you can include the logic you want to execute at each interval of the timer. For example, you might update a label to display the remaining time in a countdown, perform some action, or update UI elements based on the timer's progress.

Stopping the Timer

To stop the timer, you need to keep a reference to it and call the invalidate() method. Here's an example of how you can modify the code to stop the timer after a certain condition is met:

1var timer: Timer?
2
3@IBAction func startTimer(_ sender: UIButton) {
4 timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
5}
6
7@objc private func timerFired() {
8 // Timer logic goes here, executed every second
9
10 if /* some condition */ {
11 timer?.invalidate()
12 }
13}

In the modified code, we added a timer property to hold a reference to the timer object. When the desired condition is met (e.g., when reaching a specific time or completing a task), we call timer?.invalidate() to stop the timer.

Wrapping Up

Congratulations! You have learned how to trigger a timer function in iOS development when a UIButton is clicked using Swift. Remember that timers can be powerful tools for implementing various time-based functionalities in your apps. Take advantageof the Timer class in Swift to create countdown timers, interval-based tasks, or any other functionality that requires timed events. By handling button click events and implementing timer logic, you can add dynamic and interactive features to your iOS applications.