且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在iPhone的uilabel上显示倒数?

更新时间:2023-02-01 16:07:20

首先,在关闭应用程序后无法保持计时器运行. iPhone上根本不允许使用后台应用程序.有一些方法可以用计时器来伪造它(在应用程序退出时保存时间戳,并在启动后检查其时间),但无法解决计时器在应用程序启动前耗尽的情况上.

First off, there's no way to keep the timer running after your app is closed. Background apps simply aren't allowed on the iPhone. There are ways to fake it with a timer (save a timestamp when the app exits, and check it against the time when it starts back up), but it won't handle the case where your timer runs out before the app is started back up.

至于用倒计时更新UILabel,NSTimer可能可以工作.像这样,假设您在类中有一个NSTimer计时器,一个int secondsLeft和一个UILabel countdownLabel:

As for updating the UILabel with the countdown, a NSTimer would probably work. Something like this, assuming you have a NSTimer timer, an int secondsLeft, and a UILabel countdownLabel in your class:

创建计时器:

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

updateCountdown方法:

The updateCountdown method:

-(void) updateCountdown {
    int hours, minutes, seconds;

    secondsLeft--;
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}

我在其中一个应用中执行了类似的操作,但是现在没有方便的代码.

I do something similar in one of my apps, but don't have the code handy right now.