使用ReactiveCocoa 實現簡單的驗證碼按鈕
阿新 • • 發佈:2019-01-04
1 建立按鈕
UIButton *yzmButton = [UIButton buttonWithType:UIButtonTypeCustom];
yzmButton.backgroundColor = [UIColor orangeColor];
yzmButton.titleLabel.font = [UIFont systemFontOfSize:13];
[yzmButton setTitle:@"獲取驗證碼" forState:UIControlStateNormal];
[yzmButton addTarget:self action:@selector(startTime:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:yzmButton];
[yzmButton mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(weakSelf.lastLabel.mas_bottom).offset(15); make.centerX.mas_equalTo(weakSelf.mas_centerX);
make.size.mas_equalTo(CGSizeMake(90, 40));
}];
2 實現點選方法
-(void)startTime:(UIButton *)l_timeButton{
__block int timeout=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(timeout<=0){ //倒計時結束,關閉
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
//設定介面的按鈕顯示 根據自己需求設定(倒計時結束後呼叫)
[l_timeButton setTitle:@"傳送驗證碼" forState:UIControlStateNormal];
//設定不可點選
l_timeButton.userInteractionEnabled = YES;
l_timeButton.backgroundColor = [UIColor orangeColor];
});
}else{
// int minutes = timeout / 60; //這裡註釋掉了,這個是用來測試多於60秒時計算分鐘的。
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
dispatch_async(dispatch_get_main_queue(), ^{
//設定介面的按鈕顯示 根據自己需求設定
NSLog(@"____%@",strTime);
[l_timeButton setTitle:[NSString stringWithFormat:@"%@秒後可重新發送",strTime] forState:UIControlStateNormal];
//設定可點選
l_timeButton.userInteractionEnabled = NO;
l_timeButton.backgroundColor = [UIColor lightGrayColor];
});
timeout--;
}
});
dispatch_resume(_timer);
}