【iOS】タイマー(NSTimer)を実装:iPhoneアプリ内にカウントダウンタイマーを実装する
今回はクイズアプリでよく見かける「カウントダウンタイマー」を作成してみます。
タイマーの設定
まずは、ヘッダーファイルにNSTimerを宣言します。
NSTimer *timer; //クイズ中の経過時間を生成する int countDown; //設定時間
実装ファイルにタイマーの設定を記述します。
timer = [NSTimer scheduledTimerWithTimeInterval:1 target: self selector:@selector(TimerAction) userInfo:nil repeats:YES]; countTime = 60.0 // 設定時間「60秒」
scheduledTimerWithTimeIntervalは一定時間毎にタイマーを発生させる時間を設定します。
selectorはタイマー実行時に呼び出すメソッドを指定します。repeatsはタイマーの実行を繰り返すのであれば「YES 」指定します。
次に起動したタイマー(TimerAction)からコールされたメソッドを設定します。
-(void)TimerAction{ if(countDown>0){ countDown--; [timeLabel setText:[NSString stringWithFormat:@"%d",countDown]]; // ラベルに時間を表示 }else{ [timer invalidate]; // タイマーを停止する NSLog(@"---------タイムオーバ-----------"); } }
コメントをどうぞ