iOS造轮子系列-倒计时发送验证码按钮

作者: 东方_未明 | 来源:发表于2016-07-28 23:33 被阅读321次

    倒计时发送验证码按钮基本每个项目都会有, 这里我写一下自己的按钮, 项目紧, 没有好好的打磨, 只分享一下扩充一下思路

    效果.gif

    代码如下: (自定义按钮)

    @interface GYCodeButton : UIButton
    
    - (void)buttonClickWithTimer:(NSTimeInterval)second callBack:(void(^)(GYCodeButton *button))block;
    
    @end
    
    @interface GYCodeButton ()
    
    @property (nonatomic, copy)void(^block)(GYCodeButton *button);
    @property (nonatomic, weak) NSTimer *timer;
    @property (nonatomic, assign) int second;
    @property (nonatomic, assign) int totalSecond;
    @end
    
    
    @implementation GYCodeButton
    
    - (void)willMoveToSuperview:(UIView *)newSuperview
    {
        [super willMoveToSuperview:newSuperview];
        self.layer.borderWidth = 1.0f;
        self.layer.cornerRadius = 5;
        [self setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
    
    
    - (void)buttonClickWithTimer:(NSTimeInterval)second callBack:(void(^)(GYCodeButton *button))block
    {
        _second = second;
        _totalSecond = second;
        _block = [block copy];
        [self addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    - (void)click:(GYCodeButton *)button
    {
        button.enabled = NO;
        [self setTitle:[NSString stringWithFormat:@"%zd秒后重新发送", _totalSecond] forState:UIControlStateDisabled];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(code) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        _block(button);
    }
    
    - (void)code
    {
        [self setTitle:[NSString stringWithFormat:@"%zd秒后重新发送", --_second] forState:UIControlStateDisabled];
        if (_second <= 0) {
            if ([_timer isValid]) {
                [_timer invalidate];
                _second = _totalSecond;
                _timer = nil;
                self.enabled = YES;
            }
        }
    }
    

    使用如下:

     [self.codeButton buttonClickWithTimer:60 callBack:^(GYCodeButton *button) {
            // 这里发送请求
      
     }];
    

    相关文章

      网友评论

        本文标题:iOS造轮子系列-倒计时发送验证码按钮

        本文链接:https://www.haomeiwen.com/subject/rjtzjttx.html