美文网首页
UIButton 倒计时

UIButton 倒计时

作者: _风雨 | 来源:发表于2021-08-30 16:47 被阅读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);
    }
    

    相关文章

      网友评论

          本文标题:UIButton 倒计时

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