how to show countdown on uilabel in iphone?

久未见 提交于 2019-11-30 02:22:34

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.

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:

Create the timer:

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

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.

This code is wrong.

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

It should be.

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

you can keep your timer running when your application did enters background ,

as @shawn craver told u you cant do this but you can do this when application enters into background ("not terminates") which is a different event applicationDidEnterBackground and with that you will need some multithreading GCD(grand central dispatch).

plase refer this link

set a timer in ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!