问题
I use UIDatePicker
to implement a countdown timer.After loading viewdatePickerMode
set CountDownTimer:
- (void)viewDidLoad {
[super viewDidLoad];
self.countDownTimer.datePickerMode=UIDatePickerModeCountDownTimer;
}
First,set the countdown time in UIDatePicker
,then press the button to start the countdown:
- (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];
}
call 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 can execute properly, but when I jump out of this view and will not perform timer is zero, how do I operate the timer can be sustained after the jump view?
回答1:
I think you can do:
- When you jump out the view, let save state at this time to NSUserDefaults
- The remain time, maybe in seconds
- The current system time at that time, exam: 13:20:15
- When you open the view again:
- Get current system time, sub it with saved system time (A)
- Sub saved remain time (in seconds) with (A) and continue to countdown.
Just a idea, but hope it helps
回答2:
The best and clean way to create a singleton class and declare your timer inside as a property inside it . so there is only one instance of the timer object throughout the application .
Another way is to declare timer in the app delegate class which also holds the object throughout the application
来源:https://stackoverflow.com/questions/31200859/how-to-continue-the-countdown-timer-after-closing-viewcontroller