ios 实现倒计时的两种方式
更新时间:2017年01月22日 13:59:02 作者:于海明
这篇文章主要介绍了ios实现倒计时的两种方式,第一种方式使用NSTimer来实现,第二种方式使用GCD来实现。具体内容详情大家参考下本文
方法1:使用NSTimer来实现
主要使用的是NSTimer的scheduledTimerWithTimeInterval方法来每1秒执行一次timeFireMethod函数,timeFireMethod进行倒计时的一些操作,完成时把timer给invalidate掉就ok了,代码如下:
secondsCountDown = 60;//60秒倒计时
countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
-(void)timeFireMethod{
secondsCountDown--;
if(secondsCountDown==0){
[countDownTimer invalidate];
}
}
方法2:使用GCD来实现
代码如下:
__block int timeout=300; //倒计时时间
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _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){ //倒计时结束,关闭
dispatch_source_cancel(_timer);
dispatch_release(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
//设置界面的按钮显示 根据自己需求设置
。。。。。。。。
});
}else{
int minutes = timeout / 60;
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%d分%.2d秒后重新获取验证码",minutes, seconds];
dispatch_async(dispatch_get_main_queue(), ^{
//设置界面的按钮显示 根据自己需求设置
。。。。。。。。
});
timeout--;
}
});
dispatch_resume(_timer);
以上所述是小编给大家介绍的ios实现倒计时的两种方式,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
相关文章
VIVO手机上del键无效OnKeyListener不响应的原因及解决方法
最近有用户反馈VIVO手机上回出现,Del键无效的问题,最后找到问题所在是EdiText的OnKeyListener没有响应,下面通过本文给大家分享下解决方案2016-12-12
iOS获取当前设备型号等信息(全)包含iPhone7和iPhone7P
这篇文章主要介绍了iOS获取当前设备型号设备信息的总结包含iPhone7和iPhone7P,包括ios7之前之后的获取方式,本文接的非常详细,具有参考借鉴价值,需要的朋友可以参考下2016-10-10


最新评论