10

現在時刻から特定の日付までのカウントダウンを行い、その値をラベルに表示したいと考えています。NSTimer のチュートリアルをいくつか見ましたが、それらを自分の状況に適用する方法がわかりませんでした。

NSTimeInterval TimeInterval = [aString doubleValue]; 
NSDate* upperDate = [aDate dateByAddingTimeInterval:TimeInterval];
NSDate* Today = [NSDate date];

//cell.myLabel.text = here i should write a countdown.

コードが不十分で申し訳ありません。私は通常、ここで質問する前に自分のコードを書き込もうとしますが、今回は何を書くべきかわかりませんでした。

編集 だから、PartiallyFiniteの答えで、タイマーを設定する方法を考え出しました。しかし、私はテーブルビューを使用しているため、MyTimerLabel の繰り返しメッセージを実装できませんでした。ここで私がやったこと:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyCell";
    MekanListesiViewCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }


    aClass *aC = [myArray objectAtIndex:indexPath.row];
    NSTimeInterval TimeInterval = [aC.aTimeIntervalwithString doubleValue];
    NSDate* UpperDate = [aC.aNSDate dateByAddingTimeInterval:TimeInterval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:[NSDate date] toDate:UpperDate options:0];
    NSInteger days     = [dateComponents day];
    NSInteger months   = [dateComponents month];
    NSInteger years    = [dateComponents year];
    NSInteger hours    = [dateComponents hour];
    NSInteger minutes  = [dateComponents minute];
    NSInteger seconds  = [dateComponents second];
    NSString *countdownText = [NSString stringWithFormat:@"%d Days %d:%d:%d", days, hours, minutes, seconds];
    cell.countdownText= countdownText;
    [self performSelector:@selector(updateCoundown)]; // The delay is in seconds, make it whatever you want.


    return cell;
}
At myCellView.h
@interface MekanListesiViewCell : UITableViewCell
@property (nonatomic, weak) IBOutlet UILabel *MyTimerLabel;
@property(weak)NSString *countdownText;
at myCellView.m

-(void)updateCoundown{

       MyTimerLabel.text = countdownText;
    [self performSelector:@selector(updateCoundown) withObject:nil afterDelay:1];
}

MyTimerLabel には何も表示されません。

4

4 に答える 4

19

この回答のコードを使用して(例を完全にするためにコピーを以下に貼り付けます)、カウントダウン期間の個々のコンポーネントを取得します。

- (void)updateCountdown {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *startingDate = [dateFormatter dateFromString:@"2005-01-01"];
    NSDate *endingDate = [NSDate date];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];

    NSInteger days     = [dateComponents day];
    NSInteger months   = [dateComponents month];
    NSInteger years    = [dateComponents year];
    NSInteger hours    = [dateComponents hour];
    NSInteger minutes  = [dateComponents minute];
    NSInteger seconds  = [dateComponents second];

次に、これらすべての数値を含む文字列を作成できます。

    NSString *countdownText = [NSString stringWithFormat:@"%d Years %d Months %d Days %d Hours %d Minutes %d Seconds", days, months, years, hours, minutes, seconds];
    cell.myLabel.text = countdownText;

次に、performSelector:withObject:afterDelay:指定された遅延の後にこのメソッドが再度呼び出されるようにするために使用できます (遅延は秒単位であることに注意してください)。

    [self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1];
}
于 2013-05-20T08:25:01.877 に答える
2

NSDate *startDate,*EndDate; のようなメンバー変数を宣言します。unsigned long countDownSeconds;

あなたの条件に従って

-(void)setUpCountDown{
    startDate = [NSDate date]; //Current time
    NSDate *endDate = [startDate dateByAddingTimeInterval:10000]; //some future date
    NSTimeInterval milliseconds = [endDate timeIntervalSinceDate:startDate];/////will give time in milliseconds
    countDownSeconds = (unsigned long)milliseconds/1000;
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:nil repeats:YES];
}

-(void)countDown:(NSTimer *)timer{
    if (countDownSeconds<=0) {
        [timer invalidate];
        timer = nil;
    }
    NSLog(@"Time Elapsed in seconds %d", countDownSeconds);
    countDownSeconds--;
}
于 2013-05-20T09:48:47.330 に答える
1
let formatter = NSDateFormatter()
let userCalendar = NSCalendar.currentCalendar()
let requestedComponent: NSCalendarUnit = [
    //NSCalendarUnit.Month,
    //NSCalendarUnit.Day,
    NSCalendarUnit.Hour,
    NSCalendarUnit.Minute,
    NSCalendarUnit.Second

]
func printTime() {
    formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
    let startTime = NSDate()
    let endTime = formatter.dateFromString("12/25/16 8:00:00 a")
    let timeDifference = userCalendar.components(requestedComponent, fromDate: startTime, toDate: endTime!, options: [])
    self.TimeLabel.text = " \(timeDifference.hour)Hours \(timeDifference.minute)Minutes \(timeDifference.second) Seconds"
}

//Put this in your initialiser

let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(myProject.printTime), userInfo: nil, repeats: true)
    timer.fire()

このスレッドが非常に古いことは知っていますが、これはSwiftで行う方法です

于 2016-07-31T19:53:03.747 に答える