iOS中倒计时

方法一:使用NSTimer来实现(比较适用于发送短信验证码倒计时)

主要是利用NSTimer的scheduledTimerWithTimeInterval方法来每秒执行一次changeTime方法

//创建一个Timer,每秒执行一次changeTime:方法

NSTimer * timer =[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTime:) userInfo:nil repeats:YES];

//changeTime

-(void)changeTime:(NSTimer*)timer

{

//点击获取验证码的btn

UIButton * button = (UIButton*)[self.view viewWithTag:99];

if (count == 0) {

//完成后invalidate掉

[timer invalidate];

//59s倒计时

count = 59;

[button setTitle:@"重新获取" forState:UIControlStateNormal];

button.userInteractionEnabled = YES;

button.alpha = 1;

}

else{

[button setTitle:[NSString stringWithFormat:@"%d s",count] forState:UIControlStateNormal];

count--;

}

}

方法二:使用 GCD 来实现(比较使用于商家做某种活动的倒计时)

.h文件中定义一个Timer来控制时间

//倒计时Timer

dispatch_source_t _timer;

.m文件中实现:

//创建一个时间戳

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];

  //时间戳的格式

[dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];

  //将相同时间戳格式的NSString类型的数据转换成NSDate类型的数据

NSDate *endDate = [dateFormatter dateFromString:_EndTime];

NSDate *startDate = [dateFormatter dateFromString:_StartTime];

NSDate *currentDate = [dateFormatter dateFromString:_CurrentTime];

  //计算服务器当前时间距离活动结束的时间戳

NSTimeInterval timeInterval =[endDate timeIntervalSinceDate:currentDate];

  //计算服务器当前时间与活动开始时间的时间戳

NSTimeInterval StartToNow = [currentDate timeIntervalSinceDate:startDate];

  //倒计时时间

__block int timeout = timeInterval;

__block int StartTimeout = StartToNow;

if (timeout!=0) {

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

// 并行队列

// 并行队列可以同时处理多个任务,在不得以的情况下可以用dispatch_queue_create创建,但一般我们都要用系统预定义的并行队列,即全局队列(Global // Concurrent Dispatch Queues)。目前系统预定义了四个不同运行优先级的全局队列,我们可以通过dispatch_get_global_queue来获取它们。

//dispatch_get_global_queue第一个参数是队列的优先级,分别对应四个全局队列:

//DISPATCH_QUEUE_PRIORITY_HIGH

//DISPATCH_QUEUE_PRIORITY_DEFAULT

//DISPATCH_QUEUE_PRIORITY_LOW

//DISPATCH_QUEUE_PRIORITY_BACKGROUND

//dispatch_get_global_queue中第二个参数目前系统保留,请设置为0即可。

  //每秒执行

_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);

dispatch_source_set_event_handler(_timer, ^{

  //倒计时结束,关闭

if(timeout<=0 || StartTimeout <=0){

dispatch_source_cancel(_timer);

_timer = nil;

//在队列中运行任务

//你可以随时向一个队列中添加一个新任务,只需要调用一下dispatch_async即可:

dispatch_async(dispatch_get_main_queue(), ^{

  //可以根据自己需求设计需要显示的内容及展现格式、风格等

dayLabel.text = @"0天";

hourLabel.text = @"00 :";

minLabel.text = @"00 :";

secLabel.text = @"00";

label.text = @"抢购结束!!!";

});

}else{

label.text = @"抢购剩余时间:";

int days = (int)(timeout/(3600*24));

if (days==0) {

dayLabel.text = @"";

}

int hours = (int)((timeout-days*24*3600)/3600);

int minute = (int)(timeout-days*24*3600-hours*3600)/60;

int second = timeout-days*24*3600-hours*3600-minute*60;

dispatch_async(dispatch_get_main_queue(), ^{

if (days==0) {

dayLabel.text = @"0天";

}else{

dayLabel.text = [NSString stringWithFormat:@"%d天",days];

}

if (hours<10) {

hourLabel.text = [NSString stringWithFormat:@"0%d :",hours];

}else{

hourLabel.text = [NSString stringWithFormat:@"%d :",hours];

}

if (minute<10) {

minLabel.text = [NSString stringWithFormat:@"0%d :",minute];

}else{

minLabel.text = [NSString stringWithFormat:@"%d :",minute];

}

if (second<10) {

secLabel.text = [NSString stringWithFormat:@"0%d",second];

}else{

secLabel.text = [NSString stringWithFormat:@"%d",second];

}

});

timeout--;

}

});

dispatch_resume(_timer);

}

时间: 2024-08-28 21:57:15

iOS中倒计时的相关文章

iOS中如何实现准确的倒计时程序 &middot; 九十里

iOS中倒计时程序,考虑线程暂停场景. iOS App进入后台时,GCD线程也会跟着暂停.当程序进入前台后,GCD线程恢复.因而倒计时程序需要考虑这一点,通过加入时间的比对来实现. + (void)countDownWithLapseTime:(int)lapseTime andBlock:(void(^)(int timeLapse)) countDownBlock{ __block dispatch_source_t timer; NSTimeInterval timeInterval=la

iOS中几种数据持久化方案

概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启后可以继续访问之前保存的数据.在iOS开发中,有很多数据持久化的方案,接下来我将尝试着介绍一下5种方案: plist文件(属性列表) preference(偏好设置) NSKeyedArchiver(归档) SQLite 3 CoreData 沙盒 在介绍各种存储方法之前,有必要说明以下沙盒机制.iOS程序默认情况下只能访问程序自己的目录,这个目录被称为"沙盒". 1.结构 既然沙盒就是一个文件夹,那就看看里面有什么吧

iOS中UIWebView的使用详解

iOS中UIWebView的使用详解 一.初始化与三种加载方式 UIWebView继承与UIView,因此,其初始化方法和一般的view一样,通过alloc和init进行初始化,其加载数据的方式有三种: 第一种: - (void)loadRequest:(NSURLRequest *)request; 这是加载网页最常用的一种方式,通过一个网页URL来进行加载,这个URL可以是远程的也可以是本地的,例如我加载百度的主页:     UIWebView * view = [[UIWebView al

IOS中NSString的常见用法

iOS NSString的常用用法 //1.创建常量字符串. NSString *astring = @"This is a String!"; //2.创建空字符串,给予赋值. NSString *astring = [[NSString alloc] init]; astring = @"This is a String!"; //3.在以上方法中,提升速度:initWithString方法 NSString *astring = [[NSString allo

iOS中UITableViewCell的重用问题解决方案

UITableViewCell重用 为了能够保证tableViewCell能够高效的执行,Objective-c中引进了重用队列的机制,重影现象也是在重用队列时经常遇到的问题,那么如何解决这个问题呢?下面给出了几种解决办法. 第一种解决方法 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSArray *subViews = cell

iOS 中UIButton的 settitle 和 titlelabel的使用误区

UIButton中设置Titl方法包括以下几种: - (void)setTitle:(NSString *)title forState:(UIControlState)state; - (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state @property(nonatomic,readonly,retain) NSString *currentTitle; @property(n

iOS 中KVC、KVO、NSNotification、delegate 总结及区别

iOS 中KVC.KVO.NSNotification.delegate 总结及区别 1.KVC,即是指 NSKeyValueCoding,一个非正式的Protocol,提供一种机制来间接访问对象的属性.而不是通过调用Setter.Getter方法访问.KVO 就是基于 KVC 实现的关键技术之一. Demo: @interface myPerson : NSObject { NSString*_name; int      _age; int      _height; int      _w

ios中UIControl详解

上篇讲到了UITouch和UIEvent事件,简单回顾一下,UIEvent是一系列UITouch的集合,在IOS中负责响应触摸事件.另外还提到了响应者链的概念,在IOS中,所有事件有一个最先响应者,事件可以沿着响应者链向下传递. 接下来是UIControl对象 UIControl是UIView的子类,当然也是UIResponder的子类.UIControl是诸如UIButton.UISwitch.UITextField等控件的父类,它本身也包含了一些属性和方法,但是不能直接使用UIControl

IOS中的多线程【二】— NSOperation和NSOperationQueue

NSOperationQueue是一套基于Objective-c语言的API. GCD与NSOperationQueue的优缺点: NSOperationQueue:比较安全 GCD:没有NSOperationQueue安全,但使用起来简单,快速,还提供了一些操控底层的方法.实际开发中还是以GCD为主. NSOperationQueue实现多线程流程 1.定义一个任务队列. 2.定义一个任务. 3.把任务添加到队列中.一旦任务被添加到队列中,任务会马上被调度执行. 任务队列(NSOperatio