前言
项目中手机验证码登录和注册等页面都有发送验证码的需求。之前一直在使用自己创建定时器来做相应的处理,这段时间在看RAC相关方面的东西,正好看到定时器符合之前的一些设计场景,简单实现一下。
导入RAC
我练手的项目是Objective-C的项目,所以之前在podfile文件中加入pod ‘ReactiveObjC’, ‘~> 3.0.0’,直接pod install
然后,在需要的页面导入头文件#import "ReactiveObjC.h"。
具体代码
#import "ViewController.h"
#import "ReactiveObjC.h"
@interface ViewController ()
@property (nonatomic, strong) RACDisposable *btnDispose;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIButton *button = [UIButton new];
[button setTitle:@"发送验证码" forState:UIControlStateNormal];
button.backgroundColor = [UIColor blueColor];
button.layer.cornerRadius = 0;
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(100, 100, 200, 40);
[self.view addSubview:button];
//创建按钮点击的信号量,并监听点击事件
[[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
button.enabled = NO;
__block int time = 5;
//subscribeNext返回一个RACDisposable,可以用来取消订阅
self.btnDispose = [[RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
//定时器执行后,利用time来监测倒计时是否结束
time--;
NSString *title = time == 0 ? @"发送验证码" : [NSString stringWithFormat:@"请等待%d秒重发",time];
[button setTitle:title forState:UIControlStateNormal];
button.enabled = time == 0 ? YES : NO;
button.layer.cornerRadius = 15;
button.backgroundColor = [UIColor greenColor];
if(time == 0){
button.layer.cornerRadius = 0;
button.backgroundColor = [UIColor blueColor];
//取消订阅
[self.btnDispose dispose];
}
}];
}];
}
我在倒计时完成后改变了按钮的圆角和背景颜色,方便区分不同的状态。效果图如下