简体   繁体   English

如何暂停/播放 NSTimer?

[英]How to Pause/Play 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.我需要在我正在做的 0:0:0 之前启动 NSTimer,并且我点击了一个暂停按钮,如果用户点击播放,计时器必须在一段时间后暂停,它必须从暂停的时间值开始运行。 How can I pause and play in NSTimer?如何在 NSTimer 中暂停和播放? Any help?有什么帮助吗? Thanks in advance.提前致谢。

Try this shizzle... worked great for me试试这个 shizzle... 对我很有用

EDIT编辑

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];
    }
}

I used a UIButton and used this code when clicked.我使用了 UIButton 并在单击时使用了此代码。

remember to put this:记得放这个:

NSDate *pauseStart, *previousFireDate;

in your .h file在您的 .h 文件中

EDIT!编辑!

here is the countUp method.这是 countUp 方法。 forget the down method.忘记down方法。 seconds, minutes, hours are Ints秒,分钟,小时是整数

- (void)countUp
{
    seconds += 1;

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

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

}

You don't.你没有。 Instead of pausing simply invalidate and release the old timer and when the users presses Play again, create a fresh timer.而不是暂停简单地使旧计时器失效并释放,当用户再次按下播放时,创建一个新计时器。

refreshTimer should be on class level. refreshTimer应该在类级别。 Use the following code to stop the timer:使用以下代码停止计时器:

refreshTimer = [NSTimer scheduledTimerWithTimeInterval: refreshInSeconds
                                                target: self
                                              selector: @selector(refreshPage)
                                              userInfo: nil
                                               repeats: YES];
[refreshTimer invalidate];
refreshTimer = nil;

To start you can again schedule timer as Line 3要开始,您可以再次将计时器安排为第 3 行

Use following code to start timer with arguments also:使用以下代码也可以使用参数启动计时器:

timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(callMyMethod:) userInfo:[NSDictionary dictionaryWithObjectsAndKeys:web1, @"web", baseURL, @"baseURL", option1, @"option", nil] repeats:NO];

and then use然后使用

[timer invalidate];

to stop the timer.停止计时器。

I hope this code will help you.我希望这段代码能帮到你。

Thanks.谢谢。

there is no such thing as pause for NSTimer, you have to stop and start it again. NSTimer 没有暂停之类的东西,您必须停止并重新启动它。

[yourTimer invalidate]; [你的定时器失效]; //will stop the timer after which you can start it again //将停止计时器,之后您可以再次启动它

Updated answer for Swift 2 Swift 2 的更新答案

import UIKit

class ViewController: UIViewController {

  var myTimer = NSTimer()
  var time = 0 // global var

  @IBOutlet weak var counterLabel: UILabel!

  @IBAction func pauseTimer(sender: AnyObject) {
    myTimer.invalidate()
  }

  @IBAction func startTimer(sender: AnyObject) {
    myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true) 
  }

  func result() {
    time++
    counterLabel.text = String(time)
    print(time) 
  }

  override func viewDidLoad() {
    super.viewDidLoad()
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM