iOS造輪子系列-倒計(jì)時(shí)發(fā)送驗(yàn)證碼按鈕

倒計(jì)時(shí)發(fā)送驗(yàn)證碼按鈕基本每個(gè)項(xiàng)目都會(huì)有, 這里我寫(xiě)一下自己的按鈕, 項(xiàng)目緊, 沒(méi)有好好的打磨, 只分享一下擴(kuò)充一下思路

效果.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:@"獲取驗(yàn)證碼" 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秒后重新發(fā)送", _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秒后重新發(fā)送", --_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) {
        // 這里發(fā)送請(qǐng)求
  
 }];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容