Apps Amuck Blog 1日目
Hello Worldを表示するiphoneアプリを作った後に、いったい何を作ろうかと悩んでいたところ、こんなものを発見。
Apps Amuck Blog
http://appsamuck.com/blog/index.php/2008/11/01/full-list-of-31-days-of-iphone-sdk-apps/
1日1つ簡単なアプリを作ろうというもの。
1日目は、明日(深夜0時)までの残り時間を表示するアプリ。
URLの内容に沿って進めてみるものの、よくわからなくなってしまう。結局最終的に同じようなものができればいいかなということで、途中違うやり方になってしまったが、なんとか完成。
■新規プロジェクトを作成
OS > Application > View-based Applicationを選択し、「選択」ボタン
プロジェクト名:MinutesToMidnight
■InterfaceBuilder起動
"xxxViewController.xib"をダブルクリックし、Interface Builderを起動。
■ウィンドウの背景を黒に変更Attribute Inspector(デフォルトで右にあるウィンドウ)のAttributesタブのBackgroundをBlack Colorに設定。
■表示用ラベルの設定
Library(デフォルトで左にあるウィンドウ)からLabelをView(デフォルトで真ん中にあるウィンドウ)にドラッグ。適当な大きさに変更。font sizeは40ぐらい。"Label"はLibraryウィンドウの下の検索フィールドに入力すれば探せる。
LayoutのAlignmentを真ん中寄せにして、TextをRedに設定。
■MinutesTomidnightViewController.h
Xcodeに戻って、LabelとTimerの宣言。Timerは一定間隔で特定メソッドを繰り返し呼び出すのに使用する。updateLabelはラベルに表示する時刻を計算するメソッド。
@interface MinutesToMidnightViewController : UIViewController { IBOutlet UILabel *countdownLabel; NSTimer *timer; } -(void)updateLabel; @end
■MinutesTomidnightViewController.m
updateLabelメソッド詳細。
-(void)updateLabel { NSDate *now = [NSDate date]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *comps = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now]; NSInteger hour = 23 - [comps hour]; NSInteger min = 59 - [comps minute]; NSInteger sec = 59 - [comps second]; countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, min,sec]; }
updateLabelメソッドを1秒ごとに呼び出す部分
- (void)viewDidLoad { timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @selector(updateLabel) userInfo: nil repeats: YES]; [super viewDidLoad]; }
■ラベルとcountdownLabelの関連付け
InterfaceBuilderでラベルを選択。Attribute InspectorのConnectionsタブでnew Referencing Outletsの右の○をMinutesToMidnightViewController.xibのFile's Ownerにドラッグし、countdownLabelを選択。
■実行すれば動くはず。