如何暂停/播放 NSTimer? [英] How to Pause/Play NSTimer?

查看:33
本文介绍了如何暂停/播放 NSTimer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我正在做的 0:0:0 之前启动 NSTimer 并且我有一个暂停按钮,点击该按钮,如果用户点击播放,计时器必须在一段时间后暂停,它必须从暂停的时间值开始运行.如何在 NSTimer 中暂停和播放?有什么帮助吗?提前致谢.

I need to start NSTimer by 0:0:0 that I am doing and I have a Pause button on click of that the timer has to pause after some time if a user clicks play it has to run from paused value of time. How can I pause and play in NSTimer? Any help? Thanks in advance.

推荐答案

试试这个 shizzle... 对我很有用

Try this shizzle... worked great for me

编辑

老实说,我的实际代码是这样的:

To be honest my actual code is this:

-(IBAction)clicked:(id)sender
{
    if ([startStop.titleLabel.text isEqualToString:@"Start"]) 
    {
        [startStop setTitle:@"Pause" forState:UIControlStateNormal];
        [startStop setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

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

    } else if ([startStop.titleLabel.text isEqualToString:@"Pause"])
    {
        [startStop setTitle:@"Resume" forState:UIControlStateNormal];
        [startStop setTitleColor:[UIColor colorWithRed:0/255 green:0/255 blue:255/255 alpha:1.0] forState:UIControlStateNormal];

        pauseStart = [[NSDate dateWithTimeIntervalSinceNow:0] retain];
        previousFireDate = [[timer fireDate] retain];
        [timer setFireDate:[NSDate distantFuture]];

    } else if ([startStop.titleLabel.text isEqualToString:@"Resume"])
    {
        [startStop setTitle:@"Pause" forState:UIControlStateNormal];
        [startStop setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

        float pauseTime = -1*[pauseStart timeIntervalSinceNow];
        [timer setFireDate:[NSDate dateWithTimeInterval:pauseTime sinceDate:previousFireDate]];
        [pauseStart release];
        [previousFireDate release];
    }
}

我使用了 UIButton 并在单击时使用了此代码.

I used a UIButton and used this code when clicked.

记得放这个:

NSDate *pauseStart, *previousFireDate;

在您的 .h 文件中

编辑!

这里是 countUp 方法.忘记down方法.秒、分、小时都是整数

here is the countUp method. forget the down method. seconds, minutes, hours are Ints

- (void)countUp
{
    seconds += 1;

    if (seconds == 60) 
    {
        seconds = 0;
        minutes++;

        if (minutes == 60) 
        {
            minutes = 0;
            hours++;
        }
    }

}

这篇关于如何暂停/播放 NSTimer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆