ある教本のタイマーアプリを作っています。
画面遷移時に最後のviewDidAppearでアンダーバーにdisplayUpdateの戻り値を代入するのは何故ですか?
swift
1import UIKit 2 3class ViewController: UIViewController { 4 //タイマーの変数を作成 5 var timer: Timer? 6 //カウントの変数を作成 7 var count = 0 8 //設定値を扱うキーを設定 9 let settingKey = "timer_value" 10 11 12 13 override func viewDidLoad() { 14 super.viewDidLoad() 15 // Do any additional setup after loading the view, typically from a nib. 16 // UserDefaultsのインスタンス化 17 let settings = UserDefaults.standard 18 // UserDefaultsに初期値を登録 19 settings.register(defaults: [settingKey : 10]) 20 } 21 22 @IBOutlet weak var countDownLabel: UILabel! 23 24 @IBAction func SettingButtonAction(_ sender: Any) { 25 performSegue(withIdentifier: "goSetting", sender: nil) 26 } 27 28 @IBAction func startButtonAction(_ sender: Any) { 29 // timerをアンラップしてnowTimerに代入 30 if let nowTimer = timer { 31 // もしタイマーが、実行中だったらスタートしない 32 if nowTimer.isValid == true { 33 // 何も処理しない 34 return 35 } 36 } 37 38 // タイマーをスタート 39 timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.timerInterrupt(_:)), userInfo: nil, repeats: true) 40 } 41 42 @IBAction func stopButtonAction(_ sender: Any) { 43 if let nowTimer = timer { 44 if nowTimer.isValid == true { 45 nowTimer.invalidate() 46 } 47 } 48 } 49 50 // 画面の更新をする(戻り値: remainCount: 残り時間) 51 func displayUpdate() -> Int { 52 // UserDefaulsのインスタンス化 53 let settings = UserDefaults.standard 54 // 取得した秒数をtimerValueに渡す 55 let timerValue = settings.integer(forKey: settingKey) 56 // 残り時間(remainCount)を生成 57 let remainCount = timerValue - count 58 // remainCount(残り時間)えをラベルに表示 59 countDownLabel.text = "残り(remainCount)秒" 60 // 残り時間を戻り値に設定 61 return remainCount 62 } 63 // 経過時間の処理 64 @objc func timerInterrupt(_ timer:Timer) { 65 // count(経過時間)に+1していく 66 count += 1; 67 // remainCount(残り時間)が0以下のとき、タイマーを止める 68 if displayUpdate() <= 0 { 69 // 初期化処理 70 count = 0 71 // タイマー停止 72 timer.invalidate() 73 } 74 } 75 // 画面切り替えのタイミングで処理を行う 76 override func viewDidAppear(_ animated: Bool) { 77 // カウントを0にする 78 count = 0 79 // タイマーの表示を更新する 80 _ = displayUpdate() 81 } 82 83}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/02/03 02:19
2019/02/03 03:17
2019/02/03 07:45
2019/02/03 08:12
2019/02/03 08:23
2019/02/03 08:30