iOS 短信按钮倒计时代码

因iOS项目需要,短信倒计时,一直也没有写好,网上也没有找到合适要求的,今天写了一个UIButton分类,view初始化时,直接调用,比如,注册和忘记密码 共享冷却时间的~

#import <UIKit/UIKit.h>

@interface UIButton (AXCountDown)

/**
 短信倒计时事件,需要主动调用开始
 
 @param second 时长
 @param condition 条件
 @param events 事件
 */
- (void)ax_messageWithSecond:(NSInteger)second condition:(BOOL (^)())condition action:(void(^)(UIButton *button))action;


/**
 * 开始倒计时,需要主动调用比如AFN中,需要根据请求是否成功来进行开始计时,
 */
-(void)ax_beginCountDown;

/**
 * 停止倒计时,正常情况下,不需要主动调用
 */
-(void)ax_stopCountDown;

@end

 

.m文件

#import "UIButton+AXCountDown.h"

@interface UIButton ()


@end

@implementation UIButton (AXCountDown)

/** 记录初始化时间 */
static NSInteger _allSecond;


/** 显示倒计时的时间 */
static NSInteger _countDownSecond;


/**
 短信倒计时事件,需要主动调用开始
 
 @param second 时长
 @param condition 条件
 @param events 事件
 */
- (void)ax_messageWithSecond:(NSInteger)second condition:(BOOL (^)())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];
}


@end


 


 

demo:

 //发送短信验证事件~
    [self.verBtn ax_messageWithSecond:60 condition:^BOOL{
         if (![self.phoneTF.text ax_isChinaPhoneNumber]) {
             [MBProgressHUD showWarning:@"请输入正确的手机号"];
             return NO ;
         }else
         return YES;
     } action:^(UIButton *button) {
         [self setupVerAFN:button];
     }];

 

posted @ 2017-03-27 17:18  liu_weixing  阅读(542)  评论(0编辑  收藏  举报