如何用10秒创建倒计时?

mik*_*ike 2 cocoa-touch nstimer countdown ios

我已经在第二次创建倒计时了,比方说10秒,但我想让它更精确

到10.0并将其显示在标签上,它是如何做到的?提前致谢

这就是我现在所做的"第二次"倒计时

我的NSTimer

counterSecond = 10
NSTimer timer1 = [NSTimer scheduledTimerWithTimeInterval : 1
    Target:self selector:@selector (countLabel) userInfo:nil repeats:YES];



-(void)countLabel:
counterSecond --;

self.timerLabel.text = [NSString stringWithFormat @"%d", counterSecond];
Run Code Online (Sandbox Code Playgroud)

Bla*_*rog 15

我会使用开始日期/时间来跟踪倒计时.因为iOS可以延迟为其他任务触发定时器.

- (void)countdownUpdateMethod:(NSTimer*)theTimer {
    // code is written so one can see everything that is happening
    // I am sure, some people would combine a few of the lines together
    NSDate *currentDate = [NSDate date];
    NSTimeInterval elaspedTime = [currentDate timeIntervalSinceDate:startTime];

    NSTimeInterval difference = countdownSeconds - elaspedTime;
    if (difference <= 0) {
        [theTimer invalidate];  // kill the timer
        [startTime release];    // release the start time we don't need it anymore
        difference = 0;         // set to zero just in case iOS fired the timer late
        // play a sound asynchronously if you like
    }

    // update the label with the remainding seconds
    countdownLabel.text = [NSString stringWithFormat:@"Seconds: %.1f", difference];
}

- (IBAction)startCountdown {
    countdownSeconds = 10;  // Set this to whatever you want
    startTime = [[NSDate date] retain];

    // update the label
    countdownLabel.text = [NSString stringWithFormat:@"Seconds: %.1f", countdownSeconds];

    // create the timer, hold a reference to the timer if we want to cancel ahead of countdown
    // in this example, I don't need it
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector     (countdownUpdateMethod:) userInfo:nil repeats:YES];

    // couple of points:
    // 1. we have to invalidate the timer if we the view unloads before the end
    // 2. also release the NSDate if don't reach the end
}
Run Code Online (Sandbox Code Playgroud)