LoginSignup
12
12

More than 5 years have passed since last update.

iOS 7 でカウントダウンタイマーを実装する

Last updated at Posted at 2014-06-11

iOSのゲームアプリを作っていて、「残り時間」を実装する必要があったので、その方法のメモ。

NSTimerを使う

※2014/06/12修正しました。
カウントダウンする必要のあるViewControllerのヘッダーファイルにNSTimerのインスタンスを宣言しておいて、
iOS7だとPrivate変数は無名カテゴリに入れてしまうの方がアクセサとか作ってくれていいっぽいです。

※修正前

ViewController1.h
@interface ViewController1 : UIViewController
{
    int time;
    NSTimer* countdown_timer;
}

※2014/06/12修正後

ViewController1.m
@interface ViewController1()
@property (nonatomic)         int time;
@property (nonatomic, strong) NSTimer* countdown_timer;

実装ファイルでタイマーの設定をします。

ViewController1.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    countdown_timer = [NSTimer scheduledTimerWithTimeInterval:1 
                       target:self 
                       selector:@selector(update) 
                       userInfo:nil 
                       repeats:YES];
    time = 30;
    [countdown_timer fire];
}

scheduledTimerWithTimeInterval:1の部分は、1秒ごとにupdate関数を呼び出すという設定です。
repeatsをYESに設定することで、繰り返し実行されます。
あとは、update関数の中身に、timeをデクリメントする処理を書けばカウントダウンされます。

ViewController1.m
- (void)update
{
    if (time <= 0.0) {
        [countdown_timer invalidate];
    }
    else {
        time--;
    }
}

invalidateでタイマーを止めています。

表示の仕方

残り時間を表示するには、labelを用意して、そのlabelのtextに残り時間をNSStringに変換して入れます。
[NSString stringWithFormat:@"%d",time];で簡単に変換できます。

12
12
2

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