【swift】swift4:Timerを利用して定期処理実行をおこなう方法
Swift4で定期的に処理を実行するTimerについて
以下のように記述して実行。
例)
エミュレータを起動するとコンソールに1秒ごとに数値がカウントアップしていく。
アプリ画面内のボタン [@IBAction func stop(_ sender: Any)] をクリックするとカウントが停止する。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import UIKit class ViewController: UIViewController { var timer = Timer() //processing count var count = 0 override func viewDidLoad() { super.viewDidLoad() //timer処理 timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timer) in self.count += 1 //self.count値をコンソールへ出力 print(self.count) }) } //bottonクリック時の処理 @IBAction func stop(_ sender: Any) { //timer無効化 timer.invalidate() } } |