ios4 - iPhone : How to code a reducing countdown timer?

标签 ios4 nstimer

我想使用 UILabel 显示倒数计时器将从 5 和 开始每秒减少 1 喜欢:

5
4
3
2
1

最后在达到 0 时隐藏标签。

我尝试使用 NSTimer scheduledTimerWithTimeInterval 对其进行编码但惨败。

请帮我。

最佳答案

我只是在做类似的事情。我的代码中有一个名为 timeReamin 的 UILabel。它每秒更新一次,直到达到 0,然后显示警报。我必须警告您,由于计时器与您的 UI 在同一线程上运行,您可能会遇到一些抖动。我还没有解决这个问题,但这适用于简单的计时器。这是我正在使用的代码:

- (void)createTimer {       
    // start timer
    gameTimer = [[NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES] retain];
    [[NSRunLoop currentRunLoop] addTimer:gameTimer forMode:NSDefaultRunLoopMode];
    timeCount = 5; // instance variable
}

- (void)timerFired:(NSTimer *)timer {
    // update label
    if(timeCount == 0){
        [self timerExpired];
    } else {
        timeCount--;
        if(timeCount == 0) {
            // display correct dialog with button
        [timer invalidate];
        [self timerExpired];
         }
    }
    timeRemain.text = [NSString stringWithFormat:@"%d:%02d",timeCount/60, timeCount % 60];
}


- (void) timerExpired {
   // display an alert or something when the timer expires.
}

想出了一个消除抖动的线程解决方案。在viewDidLoad方法或applicationDidFinishLaunching中,需要这样一行:
[NSThread detachNewThreadSelector:@selector(createTimer) toTarget:self withObject:nil];

这将使用 createTimer 方法启动一个线程。但是,您还需要更新 createTimer 方法:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
// start timer
gameTimer = [[NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES] retain];
[[NSRunLoop currentRunLoop] addTimer:gameTimer forMode:NSDefaultRunLoopMode];
[runLoop run];
[pool release];

其中大部分是标准的线程入口例程。该池用于线程所采用的托管内存策略。如果您使用垃圾收集,则不需要这样做,但这不会造成伤害。 runloop 是一个事件循环,当时间每秒过去时,它会连续执行以生成事件。在你的主线程中有一个自动创建的 runloop,这是一个特定于这个新线程的 runloop。然后注意到最后有一个新的语句:
[runLoop run];

这确保线程将无限期地执行。您可以管理计时器,例如重新启动它或在其他方法中将其设置为不同的值。我在代码的其他地方初始化了我的计时器,这就是该行已被删除的原因。

关于ios4 - iPhone : How to code a reducing countdown timer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4428486/

相关文章:

objective-c - 在 uitableviewcell 中制作一个 "load more"按钮?

iphone - iTunes 应用内购买

objective-c - NSEventTrackingRunLoopMode - 这总是运行?

ios - 当 NSTimer 启动时会发生什么

iphone - 当特定的 nsdate 已过时触发方法

ios - 如何使多次启​​动的 NSTimer 失效

iphone - 特定版本轻量级迁移后自定义代码执行

ios - 检查下载的 mp4 文件是否已正确下载以播放。 - 苹果手机SDK

objective-c - 如何在 iPhone sdk 上执行多任务?

cocoa-touch - 如何用十分之一秒创建倒计时?