在iOS开发中,需要手机号注册等功能,发送短信,需要倒计时冷却,一直没有找到合适的封装封装方法,自己进行了封装,整个APP共享时间(主要为服务器短信压力),UIButton分类代码如下:
.h文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<a href='http://www.jobbole.com/members/强哥哥'>@interface</a> UIButton (AXCountDown) /** 短信倒计时事件,需要主动调用开始 @param second 时长 @param condition 条件 @param events 事件 */ - (void)ax_messageWithSecond:(NSInteger)second condition:(BOOL (^)(void))condition action:(void(^)(UIButton *button))action; /** * 开始倒计时,需要主动调用比如AFN中,需要根据请求是否成功来进行开始计时 */ -(void)ax_beginCountDown; /** * 停止倒计时,正常情况下,不需要主动调用 */ -(void)ax_stopCountDown; @end |
.m文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
#import "UIButton+AXCountDown.h" #import "UIButton+AXTool.h" <a href='http://www.jobbole.com/members/强哥哥'>@interface</a> UIButton () <a href="http://www.jobbole.com/members/q762876724">@end</a> @implementation UIButton (AXCountDown) /** 记录初始化时间 */ static NSInteger _allSecond; /** 显示倒计时的时间 */ static NSInteger _countDownSecond; /** 短信倒计时事件,需要主动调用开始 @param second 时长 @param condition 条件 @param events 事件 */ - (void)ax_messageWithSecond:(NSInteger)second condition:(BOOL (^)(void))condition action:(void(^)(UIButton *button))action{ [self setTitleColor:[UIColor lightTextColor] forState:UIControlStateDisabled]; if (_allSecond <=0) { _allSecond = second; }else{ _allSecond = _allSecond; } if (_countDownSecond>0) { [self ax_beginCountDown]; } [self ax_addTargetBlock:^(UIButton *button) { _countDownSecond = second; if (condition==nil) { action(self); }else{ BOOL success = condition(); if(success==YES){ action(self); } } }]; } -(void)ax_stopCountDown{ self.enabled = YES; _countDownSecond = _allSecond; } static NSTimer *_timer = nil; -(void)ax_beginCountDown{ if (_countDownSecond<=0) { return; } self.enabled = NO; [_timer invalidate]; _timer =[NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) { if (_countDownSecond <= 0) { [timer invalidate]; self.enabled = YES; return; } NSString *text = [NSString stringWithFormat:@"%lds后重新获取",(long) _countDownSecond]; self.titleLabel.text = text;//防止闪烁 [self setTitle:text forState:UIControlStateDisabled]; _countDownSecond--; }]; [_timer fire]; } <a href="http://www.jobbole.com/members/q762876724">@end</a> |