2011-07-26 17 views
3

私は2つの時間があります.1つは直接文字列(@ "21:00")として取り出され、その他は現在の時間です。私は21:00に達するまでにどれだけの時間が残っているかを示すカウントダウンタイマーを表示したい。iPhoneのカウントダウンタイマー

たとえば:現在の時間が17:30の場合、私が使用するラベルには「3時間30分残っています」と表示されます。 ありがとう

+0

私の答えを参照してください、私はこの中で、このようなinteresrtを取るためにあなたが正確に何を求めて –

+0

アレックスthankyoyを行い、完全な作業のサンプルコードを提供してきました。今私はちょうど私が必要としているもので終わった。ありがとう.. –

答えて

9

OKは完全にテストされたサンプルコードgithubで、私の答えを完全に改訂し、問題の完全な解決策を作成しました。

お楽しみください:)

+0

OK私の最新のサンプルコードを参照 –

+0

この時間を現在の時間と比較し、バックワードを実行するタイマーとしてラベルに表示します。 –

+0

私は1分tghanksを参照してください –

0

をあなたは毎秒を発射することNSTimerを作成します。

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(tickClock) userInfo:nil repeats:YES]; 

を、それが発火すると、あなたが方法を入力します。そこで

- (void)tickClock; 

を、日付を比較しますあなたは現在の日付である[NSData currentDate]と対比しています。 distanceBetweenDatesを秒単位で指定されている

NSTimeInterval distanceBetweenDates = [currentDate timeIntervalSinceDate:yourDate]; 

同様

。このような何かがそれを行う必要があります

NSInteger year = 2011; 
NSInteger month = 8; 
NSInteger day = 26; 
NSInteger hour = 21; 
NSInteger minute = 0; 
NSInteger second = 0;  


NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSDateComponents *components = [[NSDateComponents alloc] init]; 
[components setYear:year]; 
[components setMonth:month]; 
[components setDay:day]; 
[components setHour:hour]; 
[components setMinute:minute]; 
[components setSecond:second]; 
    NSDate *date = [calendar dateFromComponents:components]; 
[components release]; 
+0

私は日付を持っていない!私は21時に言った文字列しか持っていません。私は何をするだろうか? –

+0

私の更新されたポストを参照してください –

3

応じNSDateを作成し、あなたの文字列から日付を作成するには

。残りの時間は秒単位で表示されます。次に、他の答えに示されているように、標準タイマーのものにする必要があります。

//assumption: targetTime is after now 
NSString *targetTime = @"21:00"; 

//split our time into components 
NSArray *timeSplit = [targetTime componentsSeparatedByString:@":"]; 

NSUInteger hours = [[timeSplit objectAtIndex:0] intValue]; 
NSUInteger minutes = [[timeSplit objectAtIndex:1] intValue]; 

NSDate *now = [NSDate date]; 

//split now into year month day components 
NSCalendar *currentCalendar = [NSCalendar currentCalendar]; 
NSDateComponents *dateComponents = [currentCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:now]; 

//set our time components from above 
[dateComponents setHour:hours]; 
[dateComponents setMinute:minutes]; 

NSDate *targetDate = [currentCalendar dateFromComponents:dateComponents]; 

//ensure target is after now 
if ([targetDate timeIntervalSinceDate:now] < 0) 
{ 
    NSDateComponents *day = [[NSDateComponents alloc] init]; 
    [day setDay:1]; 

    targetDate = [currentCalendar dateByAddingComponents:day toDate:targetDate options:0]; 
} 

NSTimeInterval timeRemaining = [targetDate timeIntervalSinceDate:now]; 
+0

私はそれをメソッドにして、タイマーメソッド内から呼び出すでしょうが、私はあなたのための練習としてそれを残します。 – Ian1971

+0

私はすでにあなたのコードを完了し、正確に何が必要なのですか。しかし、アレックスが私の質問をクリアするために取った努力のために...そして彼はまた、私が彼の答えを受け入れるように、同じものを与えてくれました! –

+0

ありがとうSadumerry。私はアレックスがポイントに値することに同意する。 – Ian1971

関連する問題