LoginSignup
0
1

swiftでカウントダウンを実装してみる

Last updated at Posted at 2023-11-05

はじめに

swiftの勉強をしていて、タイマーのカウントダウンについて勉強をしたので、
備忘録として簡単にまとめていきたいと思います。

公式ドキュメントを読み解く

Creates a timer and schedules it on the current run loop in the default mode.

上記メソッドを用いれば、タイマーの機能が使えそうなので、さらに読み進める。

class func scheduledTimer(
    timeInterval ti: TimeInterval,
    target aTarget: Any,
    selector aSelector: Selector,
    userInfo: Any?,
    repeats yesOrNo: Bool
) -> Timer

timeIntervalにインターバルの時間を、targetにタイマーが経過した際のターゲットを、selectorにタイマーが経過した際に呼び出すセレクタを、userInfoにはnilを、
repeatesには繰り返すかをbool値で設定する模様。

というわけで、1秒毎にupdateTimer関数を呼び出す処理は、以下のようになります。

Timer.scheduledTimer(timeInterval: 1.0, target: self,
                selector: #selector(updateTimer), userInfo: nil, repeats: true )

実装例

以下、1秒毎にカウントダウンをする処理となります。

ViewController.swift
import UIKit

class ViewController: UIViewController {
    var counter = 10
    var timer = Timer()

    override func viewDidLoad() {
        super.viewDidLoad()

        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self,
                selector: #selector(updateTimer), userInfo: nil, repeats: true )
    }

    @objc func updateTimer() {
        if counter > 0 {
            counter -= 1
        } else {
            timer.invalidate()
        }
    }
}

1秒毎にupdateTimer関数を呼び出し、
counterが0以上であればcounterをデクリメントし、0以下であればタイマーを無効化します。
このように実装することで、カウントダウン機能を実現することができます。

まとめ

カウントダウン機能をswiftで実装する場合は、scheduledTimerを使用する。

参考文献

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1