[Swift] How to implement the countdown function

Introduction

Since the countdown function was implemented when creating a personal application, We will share the command after the memorandum.

Please take a look at the code on GitHub. -> https://github.com/onishi-app/CountDown

environment ・ Apple Swift version 5.3 ・ XCode version 12.3

Completed form

The completed form this time is as follows. ** After tapping the button, it counts down by 1 second and the screen changes when it reaches 0 seconds. ** **

カウントダウン.gif

code

This time, with ViewController.swift, which counts down, I have defined NextViewController.swift as the screen transition destination. Since there is no particular processing in NextViewController.swift, it will be omitted.

I would like to use the Timer class to implement the countdown.

ViewController.swift



import UIKit

class ViewController: UIViewController {
      
    @IBOutlet weak var countLabel: UILabel!
    @IBOutlet weak var startButton: UIButton!
    
    var time = 5
    var timer = Timer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        countLabel.text = String(time)
        startButton.layer.cornerRadius = 10
    }
    
    //Processing when the button is pressed
    @IBAction func buttonAction(_ sender: Any) {
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
            self.time -= 1
            self.countLabel.text = String(self.time)
            
            if self.time == 0 {
                self.performSegue(withIdentifier: "next", sender: nil)
            }
        })
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        timer.invalidate()
    }
}

Code description

Nothing special is done in viewDidLoad (). It is the value of the text variable timer of Label, and the corners of the button are rounded.

ViewController.swift



override func viewDidLoad() {
    super.viewDidLoad()
    countLabel.text = String(time)   //text change
    startButton.layer.cornerRadius = 10   //Rounded corner
}

I want to start the countdown when the start button is pressed, so Defined in @IBAction func buttonAction (_ sender: Any) {}.

Use the scheduledTimer () method of the Timer class. Set withTimeInterval to 1 second and repeats to true.

Although it is a process in the method, the time value is decremented by 1 and reassigned to the Label value. By this process, the Label value will also decrease by 1 second 1 second after the button is pressed.

Since the screen transition will be performed when it reaches 0 seconds, The screen transition is performed at the location of if self.time == 0 {・ ・ ・}.

ViewController.swift



//Processing when the button is pressed
@IBAction func buttonAction(_ sender: Any) {
    timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
        self.time -= 1
        self.countLabel.text = String(self.time)

        if self.time == 0 {
            self.performSegue(withIdentifier: "next", sender: nil)
        }
    })
}

Since I want to stop the timer when performing a screen transition, the following command is described.

prepare (for segue: UIStoryboardSegue, sender: Any?) {} Is This method is called when the screen is changed by performSegue ().

In the method, timer.invalidate () is executed to stop the timer.


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    timer.invalidate()
}

at the end

The countdown function is fairly easy to implement, so please use it.

You can also use the Timer class to implement the functionality of an iPhone stopwatch. (I don't think it can be implemented only with the Timer class ...)

Thank you for watching until the end.

Recommended Posts

[Swift] How to implement the countdown function
[Swift] How to implement the LINE login function
[swift5] How to implement the Twitter share function
[Swift] How to implement the fade-in / out function
[Swift] How to implement the Twitter login function using Firebase UI ①
How to implement the breadcrumb function using gretel
[For beginners] How to implement the delete function
[Swift] How to implement the Twitter login function using Firebase UI ②
How to add the delete function
[Swift] I tried to implement the function of the vending machine
[Java] How to use the hasNext function
How to implement TextInputLayout with validation function
[Swift5] How to implement standby screen using'PKHUD'
[Processing × Java] How to use the function
[Swift5] How to implement animation using "lottie-ios"
[Behavior confirmed in December 2020] How to implement the alert display function
How to add sound in the app (swift)
How to implement the email authentication function at the time of user registration
How to implement UICollectionView in Swift with code only
How to add ActionText function
[Swift] How to use UserDefaults
How to use Swift UIScrollView
[Rails] How to implement scraping
Rails learning How to implement search function using ActiveModel
[Java] How to implement multithreading
[Swift] How to get the document ID of Firebase
I tried to implement the like function by asynchronous communication
How to implement infinite scrolling (page nate) in Swift TableView
How to use the link_to method
How to use the include? method
How to use the form_with method
How to use the wrapper class
Try to implement iOS14 Widget function
[Swift] How to use SwiftLint (cocoapods)
[Swift] How to use Unwind segue
[Swift 5] Implement UI for review function
[Swift] How to send a notification
[Rails] How to implement star rating
[Swift] How to replace multiple strings
[Swift] How to dynamically change the height of the toolbar on the keyboard
How to create a registration / update function where the table crosses
[Swift] How to display when the quiz app answers correctly [Beginner]
[Swift5] How to get an array and the complement of arrays
I tried to implement the image preview function with Rails / jQuery
[Swift UI] How to get the startup status of the application [iOS]
[Rails] How to put a crown mark on the ranking function
How to use MinIO with the same function as S3 Use docker-compose
A story about using the CoreImage framework to erase stains with Swift and implement a blur erase function
[Swift] Copy the character string to the clipboard
[swift5] How to specify color in hexadecimal
Shorten the UUID to base64 in Swift.
How to implement date calculation in Java
How to implement Kalman filter in Java
[Java] How to use the File class
How to delete the wrong migration file
How to put out the error bundling
How to delete the migration file NO FILE
[Rails] How to use the map method
[Java] How to use the toString () method
[Swift] How to fix Label in UIPickerView
[Swift] How to use Tab Bar Controller