1.Android下方法:

使用 CountDownTimer Class

new CountDownTimer(getResources().getInteger(R.integer.change_count_max_value) * 1000, 1000) {

public void onTick(long millisUntilFinished) {
valueCode.setText("" + (int)(millisUntilFinished/1000));
}

public void onFinish() {
//timeOutFlag = true;
valueCode.setText(R.string.get_code);

changeButton.setEnabled(true);
}
}.start();
}
}
});

 

2.IOS下:

思路:

  • 创建按钮, 添加点击方法;
  • 用NSTimer定时器, 每秒执行一次, 定时改变Button的title,改变Button的样式, 设置Button不可点击;
  • 若倒计时结束, 定时器关闭, 并改变Button的样式, 可以点击;

在按钮的点击事件里调用该方法:


-(void)openCountDonw{
__block NSInteger time = 59;

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(time <= 0){ //倒计时结束,关闭

dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{

//设置按钮的样式
[_getCode setTitle:NSLocalizedString(@"get_code", @"") forState:UIControlStateNormal];
_getCode.userInteractionEnabled = YES;
});

}else{

int seconds = time % 60;
dispatch_async(dispatch_get_main_queue(), ^{

//设置按钮显示读秒效果
[_getCode setTitle:[NSString stringWithFormat:@"%.2d", seconds] forState:UIControlStateNormal];
[_getCode setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
_getCode.userInteractionEnabled = NO;
});
time--;
}
});
dispatch_resume(_timer);
}



 

注意点:

 

我们在创建Button时, 要设置Button的样式:
当type为: UIButtonTypeCustom时 , 是读秒的效果.
当type为: 其他时, 是一闪一闪的效果.

 

概念:

1.__block:Block内部能够读取外部局部变量的值。但我们需要改变这个变量的值时,我们需要给它附加上__block修饰符。上述NSInteger time 变量在Block外部定义,在Block内使用了time--;

2. userInteractionEnabled:当前视图设为view.userInteractionEnabled=NO 时,当前视图不可交互,该视图上面的子视图也不可与用户交互(不可响应即被该视图忽视),响应事件传递到下面的父视图。此时其他按钮都不能点击。

3.dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

4.dispatch_source_t:精度比NSTimer高的计时器,系统自动触发,系统级别的源。

5.dispatch_resume():恢复队列 dispatch_source_cancel:取消队列

 

6.dispatch_async(queue,block)  async 异步队列,​​dispatch_async​​ 函数会立即返回, block会在后台异步执行

 

参考:

2. userInteractionEnabled : http://www.jianshu.com/p/febef5ce9adc

3.GCD基础知识集合:http://www.jianshu.com/p/1f48eb97922b

4.计时器:http://www.jianshu.com/p/faa6ffe4fac3