カウントダウンさせたい! | iPhoneアプリ開発日誌 -ZERO-

iPhoneアプリ開発日誌 -ZERO-

プログラムの事を何も知らない素人が、iPhoneアプリを開発していく上で悩んだ点や勉強した点、記録を残していきます。

自分が作ってみたいアプリには「1秒ごとにカウントダウンする」
という動作が必要で、どうにかできないものかと苦戦しておりました。
カウントダウンさせるコードはインターネット上にはあまりないんですね。

最初for文でやってみたんですけど、最終結果しか出力されなくて、
いきなり「はい時間で~す。」なんて言われて困りまして笑

色々調べてみるとNSTimerなるものが存在すると!
C言語は少し弄ったことあったんですが、Objective-Cなんてものは
名前しか知らなくて、NSTimerって初めて聞いた時ははい?って感じでした。

IBはこんな感じ。
$iPhoneアプリ開発日誌
デザインは技術の次と考えてるので、とりあえず動かすことを目標に
やってるので質素なのは勘弁を。



で、完成品はこれ。

hファイル
----------------------------------------------------------
#import

@interface CountDownViewController : UIViewController {
IBOutlet UILabel *label;
IBOutlet UIButton *start;
IBOutlet UIButton *stop;
IBOutlet UIButton *reset;
}

@property(nonatomic,retain)UIButton *start;
@property(nonatomic,retain)UIButton *stop;

-(IBAction)MyAction1:(id)sender;
-(IBAction)MyAction2:(id)sender;
-(IBAction)MyAction3:(id)sender;
-(IBAction)MyAction4:(id)sender;
@end
----------------------------------------------------------

まんまですよね笑 説明いらないと思います。


mファイル
----------------------------------------------------------
@synthesize start,stop;

NSTimer* timer;

- (void) hogeTimer {
timer = [NSTimer
scheduledTimerWithTimeInterval:1
target: self
selector:@selector(MyAction1:)
userInfo:nil
repeats:YES];
}

- (IBAction)MyAction1:(id)sender{
int labelvalue =[[label text] intValue];
labelvalue--;
[label setText:[NSString stringWithFormat:@"%d",labelvalue]];
if(labelValue==0);
[timer invalidate];
self.stop.hidden=YES;
}

-(IBAction)MyAction2:(id)sender{
[self hogeTimer]; //hogeTimerを動かし始める。
self.start.hidden= YES;
self.stop.hidden= NO;
}


-(IBAction)MyAction3:(id)sender{
[timer invalidate]; // timerをストップ
self.stop.hidden = YES;
}

-(IBAction)MyAction4:(id)sender{
[label setText:[NSString stringWithFormat:@"180"]];
self.start.hidden= NO;
}
----------------------------------------------------------
MyActionは一定時間ごとに実行させるプログラム
 →Labelの値を変数(labelValue)に格納し、1を引いた値を
  labelValueに返す(出力する)
MyAction2はStartボタンが押された時
MyAction3はStopボタンが押された時
MyAction4はresetボタンが押された時
 →Labelに180を入れて擬似的に初期化してます。


ボタンは1度押されたらリセットされるまで隠します。
隠しておかないと連打されたらバグってしまうので笑


これで一応カウントダウン自体は完成ですね。


初めて自分でめっちゃ調べて、めっちゃデバッグした
プログラムなんで結構感動もんですよ笑
よしよし、いい感じ。