「ゴルトン社長」のはじめの一歩

すげーブログ

世の中のすげーを伝える!

【iphoneアプリ開発_初心者必見】Timer(タイマー)に関するコード集

最終更新日:2020年08月14日
f:id:BlueThree:20200814204123j:plain:w500
家に引きこもっている「ゴルトン社長」です。(twitter : @GoRuton_1stStep)

人気の記事!

人生を変えたい人に向けて「はじめの一歩」を踏み出したい人にオススメ!

www.goruton.com www.goruton.com www.goruton.com www.goruton.com

1)Timer(タイマー)の基本的な利用

import UIKit

class MainViewController: UIViewController {

    var timer: Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(MainViewController.timerUpdate), userInfo: nil, repeats: true)
    }

    @objc func timerUpdate() {
        print("update")
    }

    @IBAction func buttonAction(_ sender: Any) {
        print("invalidate!!")
        self.timer?.invalidate()
    }
}
//5秒間隔で呼ばれる

// timeInterval:ループなら間隔,1度きりなら発動までの秒数
// target:メソッドを持つオブジェクト
// selector:実行するメソッド
// userInfo:オブジェクトに付ける値
// repeats:繰り返し実行するかどうか
  • 5秒間隔で呼ばれるTimerメソッドです.
  • 変数を保持しておくことでinvalidate()でタイマーを破棄することができ、実質タイマーが停止します。
  • Timerインスタンスは破棄されるので、同じインスタンスでの再開は不可能です。
  • 再開する場合は破棄した時点の時間を計算するなど、Timerインスタンスを生成し直す必要があります。

2)Timer(タイマー)の基本的な利用2

f:id:BlueThree:20190630203040p:plain:h300:w150
実装画面

import UIKit

class ViewController: UIViewController {
    let label1 = UILabel() //いないいないを表示
    let label2 = UILabel() //ばぁを表示
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    
    @IBAction func tapBtn1(_ sender: UIButton) {
        print("tap btn1") //確認用
        label2.text = ""
        label1.text = "OK"
        label1.font = UIFont(name: "HiraginoSans-W6", size:10)
        label1.sizeToFit() //フォントサイズを指定したあとにlabe.sizeToFitメソッドでラベルのサイズを文字の大きさに合わせて拡大しています。
        label1.center.x = self.view.center.x
        label1.center.y = self.view.center.y
        self.view.addSubview(label1)
        
        Timer.scheduledTimer(
            timeInterval: 0.01,
            target: self,
            selector: #selector(self.kakudai(_:)),
            userInfo: label1,
            repeats: true
        )
    }
    
    
    @IBAction func tapBtn2(_ sender: UIButton) {
        print("tap btn2")//確認用
        label1.text = ""
        label2.text = "NG"
        label2.font = UIFont(name: "HiraginoSans-W6", size:10)
        label2.sizeToFit()
        label2.center.x = self.view.center.x
        label2.center.y = self.view.center.y
        self.view.addSubview(label2)
        
        Timer.scheduledTimer(
            timeInterval: 0.005,
            target: self,
            selector: #selector(self.kakudai(_:)),
            userInfo: label2,
            repeats: true
        )
    }
    
    //userInfoにLabelを渡した場合のメソッド
    @objc func kakudai(_ sender: Timer){
        let tmpLabel = sender.userInfo as! UILabel
        tmpLabel.font = tmpLabel.font.withSize(tmpLabel.font.pointSize + 1)
        tmpLabel.sizeToFit()
        tmpLabel.center.x = self.view.center.x
        tmpLabel.center.y = self.view.center.y
        if tmpLabel.font.pointSize >= 100 {sender.invalidate()}
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}

3)Timer(タイマー)の基本的な利用3

/// 画面が閉じる直前に呼ばれる

var timer = Timer()


    //processing count
    var count = 0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(MainViewController.timerUpdate), userInfo: nil, repeats: true)

        // タイマーの設定(5秒間隔でメソッド「timerCall」を呼び出す)
        addTimer =  Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(timerCall), userInfo: nil, repeats: true)

        //timer処理
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timer) in
            self.count += 1
            //self.count値をコンソールへ出力
            print(self.count)
        })
    }

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    // タイマーを停止する
    if let workingTimer = timer{
        workingTimer.invalidate()
    }
}

4)デバイスによるTimerの違い

iPhone
  • ホームボタンを押して、アプリがバックグランドになると、タイマーのメソッド呼び出しが止まります.
  • 再びアクティブになると呼び出しが戻るようです。
AppleWatch
  • digital crownを押してHomeに戻っても、Timerは呼ばれ続けるようです。
  • 任意で止めたい場合はwillActivate()やdidDeactivate()でコントロールする必要

参考リンク先

最後に!!

f:id:BlueThree:20200805191056j:plain:w500

最後までご覧いただき、本当にありがとうございます!!

最近は、たくさんの読者さんから「コメント」や「メッセージ」が届くようになりました!!
皆さんと会話できて嬉しいですし、コメントで毎日励まされています。

ありがとうございます!

これからも、ゴルトン社長は「毎日」ブログを更新しています! www.goruton.com www.goruton.com www.goruton.com www.goruton.com www.goruton.com

皆さんから人気がある記事

www.goruton.com www.goruton.com www.goruton.com www.goruton.com www.goruton.com

まとめ記事

www.goruton.com www.goruton.com www.goruton.com www.goruton.com www.goruton.com www.goruton.com www.goruton.com