关闭后如何继续倒计时ViewController

How to continue the countdown timer after closing ViewController

我使用UIDatePicker实现倒计时timer.After加载视图datePickerMode设置CountDownTimer:

- (void)viewDidLoad {
[super viewDidLoad];
self.countDownTimer.datePickerMode=UIDatePickerModeCountDownTimer;
}

首先在UIDatePicker中设置倒计时时间,然后按下按钮开始倒计时:

- (IBAction)StartCountdown:(id)sender {
    [sender setTitle:@"Cancel" forState:UIControlStateNormal];
    countDownInterval = (NSTimeInterval)countDownTimer.countDownDuration;
    remainder = countDownInterval;
    afterRemainder = countDownInterval - remainder % 60 ;
    //call updateCountDown()
    timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateCountDown) userInfo:nil repeats:YES];
}

致电updateCountDown():

-(void)updateCountDown{
    afterRemainder --;
    int hours = (int)(afterRemainder/(60*60));
    int mins = (int)(((int)afterRemainder/60)-(hours * 60));
    int secs = (int)(((int)afterRemainder - (60 * mins) - (60 * hours *60)));
    NSString *displayText = [[NSString alloc]initWithFormat:@"%02u : %02u : %02u",hours,mins,secs];
    self.displayLabel.text = displayText;
}

Action可以正常执行,但是当我跳出这个view的时候不会执行timer为0,请问如何操作跳转view后timer才能持续?

  1. 创建单例 class 并将内部计时器声明为其中的 属性 的最佳且干净的方法。因此在整个应用程序中只有一个计时器对象实例。

  2. 另一种方法是在应用程序委托 class 中声明计时器,它也在整个应用程序中持有对象

我认为你可以做到:

  1. 跳出视图时,让此时的状态保存到NSUserDefaults
    • 剩余时间,可能以秒为单位
    • 当时系统时间,考试:13:20:15
  2. 再次打开视图时:
    • 获取当前系统时间,用保存的系统时间 (A) 代替它
    • 用(A)子保存剩余时间(以秒为单位)并继续倒计时。

一点想法,希望对你有帮助