How to implement countdown timer in ios
This article is about how to implement countdown timer in ios. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.
The effect of this countdown timer is as follows:
After setting the time of UIDatePicker as the remaining time, click the start button to start timing. UIDatePicker modifies the remaining time every 60s.
The code is as follows:
@implementation JoyViewController
NSTimer* timer;
NSInteger leftSeconds;
- (void)viewDidLoad
{
[super viewDidLoad];
//Set to use Count Down Timer mode
self.countDonwn.datePickerMode = UIDatePickerModeCountDownTime;
}
-(IBAction)clicked:(id)sender
{
//Get remaining time of settings
leftSeconds = self.countDown.countDuration;
//disable UIDatePicker control
self.countDown.enabled = NO;
//disable start button
[sender setEnabled] = NO;
//initialize a string to be used as the contents of the warning box
NSString *message = [[NSString stringWithFormat:@"Start countdown? You have [ %d] seconds left ",leftSeconds];
//Create a UIAlertView
UIAlartView * alert = [[UIAlartView alloc]initWithTitle:@"Start countdown? "
message:message
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
//Enable timer to execute tickdown method every 60s
timer = [NSTimer scheduledTimerWithTimeInterVal:60
targer:self selector:@selector(tickDown)
userInfo:nil repeates:YES];
}
- (void) tickDown
{
//Reduce the remaining time by 60s
leftSeconds -= 60;
//modify the remaining time of UIDatePicker
self.countDown.countDownDuration = leftSeconds;
if(leftSeconds