UIButton 倒计时

2021-08-30  本文已影响0人  _风雨

Swift 5.0

func showCountdownTime(_ time: Int, button: UIButton?) {
    var time = time
    
    let codeTimer = DispatchSource.makeTimerSource(flags: .init(rawValue: 0),
                                                   queue: DispatchQueue.global())
    
    codeTimer.schedule(deadline: .now(), repeating: .milliseconds(1000))  //此处方法与Swift 3.0 不同
    codeTimer.setEventHandler {
        
        time = time - 1
        
        DispatchQueue.main.async {
            button?.isEnabled = false
        }
        
        if time < 0 {
            codeTimer.cancel()
            
            DispatchQueue.main.async {
                button?.isEnabled = true
                button?.setTitle("发送验证码", for: .normal)
            }
            return
        }
        
        DispatchQueue.main.async {
            button?.setTitle("\(time)秒", for: .normal)
        }
    }
    codeTimer.activate()
}

Objective-c

+ (void)showCountdownTime:(NSUInteger)time button:(UIButton *)button {
    __block int timeout = (int)time;
    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(), ^{
                [button setTitle:@"验证" forState:UIControlStateNormal];
                button.enabled = YES;
                [button setTitleColor:[UIColor navgationbarBackgroundColor] forState:UIControlStateNormal];
            });
        }else{
            int seconds = timeout-1;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                button.enabled = NO;
                NSString *timeString = [NSString stringWithFormat:@"%@秒",strTime];
                button.titleLabel.text = timeString;
                [button setTitle: timeString forState:UIControlStateDisabled];
                [button setTitleColor:[UIColor colorWithRed:160/255.0 green:160/255.0 blue:160/255.0 alpha:1.0] forState:UIControlStateDisabled];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
上一篇下一篇

猜你喜欢

热点阅读