iPhoneのUILabelでカウントダウンする方法

このQ&Aのポイント
  • iPhoneのUILabelでカウントダウンするためには、カウントダウン処理のタイミングを間違えずに行う必要があります。
  • 通常の処理では、処理が一気に終了し、最終的な表示結果しか表示されませんが、カウントダウンを実現するためには適切なタイミングで表示を更新する必要があります。
  • そのため、NSTimerを使用して指定した時間ごとにUILabelのテキストを更新することでカウントダウンを実現することができます。
回答を見る
  • ベストアンサー

iPhoneのUILabelでカウントダウンしたい

Window-based Applicationで新規にプロジェクトを作成し、applicationを 以下のように書き足しました。 しかし、これではカウントダウンせずに1だけ表示されます。 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. [self.window makeKeyAndVisible]; UILabel *countdown = [[UILabel alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [self.window addSubview:countdown]; countdown.text = @"3"; sleep(1); countdown.text = @"2"; sleep(1); countdown.text = @"1"; return YES; } 1になるまで処理が抜けないので、これではダメなのはなんとなく理解できるのですが、 どのようにコーディングすると自動的にカウントダウンできるでしょうか? もうちょっと工夫して別スレッドからcountdown.textを更新するようにもしてみましたが、 結果は変わりませんでした。

質問者が選んだベストアンサー

  • ベストアンサー
  • harawo
  • ベストアンサー率58% (3742/6450)
回答No.1

NSTimerを使ってください。

jjk65536
質問者

お礼

NSTimer使ったらできました。 ありがとうございます。

関連するQ&A

  • Objective-C for文でのインスタンス

    既出の質問と類似してますが、解決しないので質問します。 Objective-CのNSMutableArrayを使いラベルを複数個作りならべたいのですが、 変数iを使ってラベルに番号をつける方法がわかりません。 今のコードは NSMutableArray *tiles = [NSMutableArray array]; for( int i=0; i<25; i++ ){ UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0,0, tileSize,tileSize)]; label.text=[NSString stringWithFormat:@"%d",i]; [tiles addObject:label]; [self.view addSubview:label]; } です。 これを UILabel *label%d,i = [[UILabel alloc]initWithFrame:CGRectMake(0,0, tileSize,tileSize)]; のようにして、 label0、lable1、label2、label3・・・・ というように生成するにはどうしたらいいですか? Objective-C初心者です。 よろしくお願いします。

  • iPhone IBを使用しないでUITabBarControllerを

    iPhone IBを使用しないでUITabBarControllerを実装 - (void)applicationDidFinishLaunching:(UIApplication *)application { window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // UIViewControllerを継承したクラス page1Controller = [[Page1Controller alloc] initWithNibName:nil bundle:nil]; page2Controller = [[Page2Controller alloc] initWithNibName:nil bundle:nil]; // 質問1 tabBarController = [[UITabBarController alloc] initWithNibName:nil bundle:nil]; [tabBarController setViewControllers:[NSArray arrayWithObjects:page1Controller, page2Controller, nil] animated:NO];  // 質問2 [window addSubview:tabBarController.view]; tabBarController.selectedIndex = 1; } 上記プログラムなのですが、 質問1.UITabBarControllerのsetViewControllersメソッドを利用して、     UIViewControllerのインスタンスをセットしているのですが、     setViewControllersメソッドは、     UITabBarControllerのプロパティviewControllersに     値をセットするためのセッターなのでしょうか? 質問2.[window addSubview:tabBarController.view]のviewは、     UITabBarControllerが継承しているUIViewControllerの     view(ゲッター)なのでしょうか? 上記の流れで、UITabBarControllerが、UIVeiwControllerを集約?しているので、 (@property(nonatomic, copy) NSArray *viewControllersとUITabBarControllerのヘルプに明記しているので) WindowのaddSubViewにセットするのは、UITabBarControllerのUIViewControllerのviewじゃないのかな? と初心者ながらの疑問です。 継承などの理解不足があると思いますが、ご教授の程お願いいたします

  • ナビゲーションバーのタイトルを2行で表示

    ObjctiveCを用いてiPhoneApp開発の勉強をしています。 タイトルの通り、ナビゲーションバーのタイトルを2行で表示させたいのですがうまくできないので助言をいただきたいです。 こちらのサイトを参考に進めました。 (参考)http://www.yoheim.net/blog.php?q=20121203 こちらのコードをコピペするといろいろとエラーが出てしまうのですが、 まず一行目に表示するラベルのaddSubviewするところで、 [titleView addSubview:taskMessageLabel]; のように記述されていますが、まだtaskMessageLabelは作成されていません。 また、二行目に表示するラベルのtaskMessageLabelはUILabel *taskMessageLabelとすると思うのですが、それもされていません。 いろいろと手直しをし、以下のようにしたのですが、二行目のサブタイトルしか表示されませんでした。 どのようにすれば、きちんと二行でタイトルを表示することができるのでしょうか? 回答お待ちしてます // ナビゲーションバーのtitleに表示する独自Viewを作成します。 UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)]; titleView.backgroundColor = [UIColor clearColor]; titleView.opaque = NO; // ☆☆ポイントはここ!! // 以下のように代入して、タイトルに独自Viewを表示します。 self.navigationItem.titleView = titleView; // 1行目に表示するラベルを作成して、 // 上記で作成した独自Viewに追加します。 UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 195, 20)]; titleLabel.font = [UIFont boldSystemFontOfSize:16.0f]; titleLabel.text = @"RSS"; titleLabel.textColor = [UIColor whiteColor]; titleLabel.textAlignment = NSTextAlignmentCenter; titleLabel.backgroundColor = [UIColor clearColor]; [titleView addSubview:titleLabel]; // 2行目に表示するラベルを作成して、 // 上記で作成した独自Viewに追加します。 UILabel *taskMessageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 195, 40)]; taskMessageLabel.font = [UIFont boldSystemFontOfSize:10.0f]; titleLabel.text = @"サブタイトル"; taskMessageLabel.textColor = [UIColor colorWithRed:104.0f/255.0f green:100.0f/255.0f blue:100.0f/255.0f alpha:1.0f]; taskMessageLabel.textAlignment = NSTextAlignmentCenter; taskMessageLabel.backgroundColor = [UIColor clearColor]; taskMessageLabel.adjustsFontSizeToFitWidth = YES; [titleView addSubview:taskMessageLabel];

  • iPhone SDK UIViewに追加したUIButtonが反応しな

    iPhone SDK UIViewに追加したUIButtonが反応しない。。。 インターフェイスビルダーにあるUIViewにボタンを追加した場合は、 ちゃんとボタンは反応するんですが、プログラムから追加したUIViewにボタンをおくと UIControlEventTouchUpInsideのイベントに反応しません。 一応、こちらに簡単なプロジェクトもあげておきました。 http://gemic.jp/xcode/buttonOnView.zip 詳細は、下記です。 View-Based Applicationテンプレートで作成したプロジェクト(buttonOnView) buttonOnViewViewController.h #import <UIKit/UIKit.h> @interface buttonOnViewViewController : UIViewController { UIView *theView; } @end ----------------------------------------------------------------- buttonOnViewViewController.m - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor redColor]; UIButton *btn1 = [[UIButton buttonWithType:UIButtonTypeRoundedRect]retain]; [btn1 initWithFrame:CGRectMake(60, 90, 200, 50)]; //このボタンは反応する↓ [self.view addSubview:btn1]; [btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [btn1 addTarget:self action:@selector(createView:) forControlEvents:UIControlEventTouchUpInside]; } - (IBAction)createView:(UIButton*)sender { theView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; [theView setBackgroundColor:[UIColor greenColor]]; [self.view addSubview:theView]; UIButton *btn = [[UIButton buttonWithType:UIButtonTypeRoundedRect]retain]; [btn initWithFrame:CGRectMake(60, 150, 200, 50)]; //このボタンは反応しない↓ [theView addSubview:btn]; [btn addTarget:self action:@selector(deleteView:) forControlEvents:UIControlEventTouchUpInside]; } - (IBAction)deleteView:(UIButton*)sender { NSLog(@"touch event reaction"); [theView removeFromSuperview]; } ----------------------------------------------------------------- いろいろググってみたり、DevCenterのドキュメントを探したんですが、 思ったような情報が見つからず相当はまってます。 ネットで探して見つからないってことは、凄く初歩的なことか?? と思ってるんですが、、、 どなたか、助けていただけたらありがたいです。

  • スクロールの上にある画像をフリックで変える方法とは

    今、画像を左右に数枚スクロールさせ、かつ、その画像を上や下にフリックすると各々、上や下に他の画像がでてきて、さらに拡大縮小もできるようなコードを書いています。 ViewContorller(以下、VC)にスクロールのメソッドを書き、 もう一つのPageView(UIScrollVIewクラスを親にもつ。以下、PV)に画像が拡大縮小するようなメソッドと上下のフリックのメソッドを書いています。 このPVの中で行う上下のフリックの操作によって、VCにあるスクロールの上に乗っている画像を変えたいのですが、色々と試したのですがその方法が一向にわかりません。もし宜しければ、ご教授ください。宜しくお願い致します。 xcodeは5.0です。 以下、スクロールとその上に画像をのせているpageがあるVC.mのコードです。 このpageにのっている画像をPVのほうのフリック操作で変更させたいと思っています。 - (void)viewDidLoad { [super viewDidLoad]; UIScrollView *scrollView = [[UIScrollView alloc] init]; scrollView.frame = self.view.bounds; scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 3, self.view.frame.size.height); scrollView.pagingEnabled = YES; [self.view addSubview:scrollView]; //AppdelegateでValueというプロパティをつくり、PVでのフリック操作によってこの数値が変動したら、currentpageに反映して、それに対しての画像がでてくるようにしたいつもりです。 AppDelegate *appdelegate=(AppDelegate*)[[UIApplication sharedApplication]delegate]; currentpage=appdelegate.Value; //PageViewにて、画像をいれるメソッドをsetImageでつくっています。 for (int i=1;i<4;i++) { PageView *page = [[PageView alloc] initWithFrame:self.view.bounds]; [page setImage:[NSString stringWithFormat:@"%d.%d",currentpage,i]]; page.frame = CGRectMake( self.view.frame.size.width * (i-1), 0, self.view.frame.size.width, self.view.frame.size.height ); [scrollView addSubview:page]; }

  • スクロールの上でラベルをドラッグする方法について

    現在、左右スクロールと上下フリックができるViewをタップすることでラベルがでてきて、そのラベルをドラッグできるようなコードを作っています。 具体的には、ViewController のViewの上に、画像を左右にScrollできるView(ScrollView)をのせ、その上に、それらの画像を上下にフリックすると別の画像がでてくるようなView(PageView、親クラスがUISrollView)を作成しています。 そこで、上下のフリック、スクロール、タップでラベルがでてくるのはできるようになったのですが、ラベルを認識してドラッグができる(UIPanGestureRecognizer)というのができません。 もし、おわかりになられる方がいらっしゃいましたら、お手数をおかけしますがご教授頂けたら幸いです。 以下、コードです。 xcodeは5.0です。 これらはViewContorllerの中に書いてあります。 //ScrollViewの上にPageViewクラスで作ったpageを乗せてスクロールしています。pageには画像をいれています。 for (int i=1;i<4;i++) { PageView *page = [[PageView alloc] initWithFrame:self.view.bounds]; page.delegate=self; [page setImage:[NSString stringWithFormat:@"%d",i]]; page.frame = CGRectMake( self.view.frame.size.width * (i-1), 0, self.view.frame.size.width, self.view.frame.size.height ); [scrollView addSubview:page]; //pageにタップしてproductLabelがでてくるようにしています。 [page addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrlTapREcotTap:)]]; NSLog(@"tap"); //ここでラベルのproductLabelだけに触れてドラッグできるようにしたいのですが、ドラッグができません。 UIPanGestureRecognizer *pan =[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePanGesture:)]; [productLabel addGestureRecognizer:pan]; NSLog(@"drag"); }} //ラベルをタップにより表示したり、非表示にしたりしています。 - (void)scrlTapREcotTap:(UITapGestureRecognizer *)gestureRecognizer { if(isTappFirstTime) { //put code of hide [UIView animateWithDuration:1 animations:^{ productLabel.alpha = 0; } completion: ^(BOOL finished) { productLabel.hidden = YES; }]; isTappFirstTime = NO; NSLog(@"非表示"); } else { // put code of show [UIView animateWithDuration:1 animations:^{ productLabel = [[UILabel alloc] init]; //UILabel *label = [[UILabel alloc] init]; productLabel.frame = CGRectMake(10, 10, 100, 50); productLabel.backgroundColor = [UIColor yellowColor]; productLabel.textColor = [UIColor blueColor]; productLabel.font = [UIFont fontWithName:@"AppleGothic" size:12]; productLabel.textAlignment = UITextAlignmentCenter; productLabel.text = @"hoge"; [scrollView addSubview:productLabel]; (NSLog(@"表示")); productLabel.alpha = 1; } completion: ^(BOOL finished) { productLabel.hidden = NO; }]; isTappFirstTime = YES; } } //productLabelだけがドラッグできるようにしています。 - (void) handlePanGesture:(UIPanGestureRecognizer*) sender { CGPoint location = [sender translationInView:productLabel]; CGPoint movedPoint = CGPointMake(productLabel.center.x + location.x, productLabel.center.y + location.y); productLabel.center = movedPoint; NSLog(@"dragmethod"); [sender setTranslation:CGPointZero inView:productLabel]; } お手数おかけしますが、宜しくお願いします。

  • objectiv-cで困っています。教えてください

    objectiv-cの初心者でをトライ&エラーで試しながら学習しているのですが、基本的な部分で 行き詰っており、知恵をお借りしたいと思い投稿しました。 デバイスのサイズや向きが変わってもUIViewが中央に表示させたいのですが、 UIView *uv = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)]; uv.contentMode = UIViewContentModeCenter; uv.backgroundColor = [UIColor redColor]; [self.view addSubview:uv]; としてみました。initWithFrame:CGRectMakeの部分で0,0を指定しているので左上に表示されるのは分かるのですが、サイズだけを指定してUIViewを生成する方法が分かりません。CGSizeMakeでしていした後どうすればよいのでしょうか? 中央に表示させるのにuv.contentMode = UIViewContentModeCenter;としたのですが、使い方が間違っているのでしょうか? 十分ではないかもしれませんが、調べてはみたのですが、解決できませんでした。 宜しくお願いします。

  • Xcodeの開発でエラーの解決したいです

    Xcodeでの開発で、エラーの解決できなくて困りました。 最初のViewからCoreDataを使ったTableViewへ遷移する際に落ちます。 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController; UINavigationController *navigationController = [splitViewController.viewControllers lastObject]; splitViewController.delegate = (id)navigationController.topViewController; UINavigationController *masterNavigationController = [splitViewController.viewControllers objectAtIndex:0]; MasterViewController *controller = (MasterViewController *)masterNavigationController.topViewController; controller.managedObjectContext = self.managedObjectContext; } else { UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController; MasterViewController *controller = (MasterViewController *)navigationController.topViewController; controller.managedObjectContext = self.managedObjectContext; } return YES; 上記のコードで落ちてるのですが、どうすればいいか分からないので困りました。 勉強不足で、すみません。 どのように対処すればよいか、ご教授お願いします。 ビルドして最初の画面でボタンを押して、テーブル・ビューへの遷移時に落ちて以下のエラーが表示されます。 [UINavigationController setManagedObjectContext:]: unrecognized selector sent to instance どうしても解決したいので、よろしくお願いします。

  • オブジェクトのインスタンス変数について

    AppDataというどのクラスからもアクセスできるデータモデルクラスを作り、AppDataに格納された配列のデータを viewControllerがもつリストにセットして、テーブル表示させたいのですがうまくいかないのです。 自分の考えではポインタをきちんと理解していないorオブジェクトのインスタンス変数の寿命を把握していない。 なぜ動かないのか??どういった部分を勉強するべきか??教えていただければ幸いです! プログラムは省略してあります。 AppDelegateクラス - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { AppData *share = [AppData sharedData]; //共通データクラス作成完了 viewController.list = share.responseJsonDataArray; ←●ここが動きません!! デバッグさせるとresponseJsonDataArrayが初期化されていませんでした。 } AppDataクラス +(AppData *)sharedData { if (!_appData) { _appData = [[AppData alloc] init]; } responseJsonString = [[NSString alloc] init]; responseJsonDataArray = [[NSMutableArray alloc] initWithObjects:@"kou",@"kou",nil]; ↑ここに入ったデータを呼び出してテーブル表示させたい!! return _appData; } よろしくお願い致します!!

  • iPhoneアプリプログラミング

    iPhoneアプリ開発超初心者です。 「逆引きObjective-C for iPhoneアプリ」というサイトの中の http://www.objectivec-iphone.com/UIKit/UIImageView/UIImageView.html に、画像を表示するサンプルプログラムとして - (void)viewDidLoad { [super viewDidLoad]; // UIImageViewの初期化 CGRect rect = CGRectMake(10, 10, 250, 250); UIImageView *imageView = [[UIImageView alloc]initWithFrame:rect]; // 画像の読み込み imageView.image = [UIImage imageNamed:@"lena.png"]; // UIImageViewのインスタンスをビューに追加 [self.view addSubview:imageView]; } が紹介されているのですが、 メソッド - (IBAction)executeView:(id) sender {   // 画像表示 } の中で、画面上の特定位置への画像表示を指定する方法を教えてください。 上記のサンプルプログラムとメソッドを組み合わせるようなことをするのでしょうか? なにぶん超初心者で的外れなことを言っているかもしれませんが、よろしくお願いします。