LoginSignup
5
5

More than 3 years have passed since last update.

【swift5】ストップウォッチタイマーの作り方

Last updated at Posted at 2020-01-16

キャプチャ

スクリーンショット 2020-01-16 21.44.33.png

ソース全部

githubにもアップしております!

import UIKit
class ViewController: UIViewController {
    var OurTImer = Timer()
    var TimerDisplayed = 0
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var start: UIButton!
    @IBOutlet weak var pause: UIButton!
    @IBOutlet weak var reset: UIButton!

    @IBAction func startButton(_ sender: Any) {
        OurTImer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Action), userInfo: nil, repeats: true)
    }
    @IBAction func pauseButton(_ sender: Any) {
        OurTImer.invalidate()
    }
    @IBAction func resetButton(_ sender: Any) {
        OurTImer.invalidate()
        TimerDisplayed = 0
        label.text = "0"
    }
    @objc func Action() {
        TimerDisplayed += 1
        label.text = String(TimerDisplayed)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

ソースの解説

    var OurTImer = Timer()
    var TimerDisplayed = 0
    @IBOutlet weak var label: UILabel!

Timer()のインスタンス化
TimerDisplayedは秒数を数えてくれている変数
あとは普通の変数

    @IBAction func startButton(_ sender: Any) {
        OurTImer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Action), userInfo: nil, repeats: true)
    }
    @IBAction func pauseButton(_ sender: Any) {
        OurTImer.invalidate()
    }
    @IBAction func resetButton(_ sender: Any) {
        OurTImer.invalidate()
        TimerDisplayed = 0
        label.text = "0"
    }
    @objc func Action() {
        TimerDisplayed += 1
        label.text = String(TimerDisplayed)
    }

スタートボタンを押した時

startButtonがスタートボタンを押した時の挙動

    @IBAction func startButton(_ sender: Any) {
    }

これ

OurTImer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Action), userInfo: nil, repeats: true)

//の中の

selector: #selector(Action)

は下で定義しているこれ

    @objc func Action() {
        TimerDisplayed += 1
        label.text = String(TimerDisplayed)
    }
scheduledTimer

で1秒ずつTimerDisplayedが1づつ増えていっている

ポーズボタンを押した時

    @IBAction func pauseButton(_ sender: Any) {
        OurTImer.invalidate()
    }

タイマーを止める処理

リセットボタンを押した時

@IBAction func resetButton(_ sender: Any) {
     OurTImer.invalidate()
     TimerDisplayed = 0
     label.text = "0"
}

タイマーを止める処理をして
表示を0にする

まとめ

これで完成!

参考

最近はYoutubeにも優良な情報があってプログラミングを学びたい人には天国ですね。

(変な情報もたくさんあるのでお気をつけを。)

5
5
0

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
5
5