美文网首页
ios 短信按钮倒计时

ios 短信按钮倒计时

作者: 老公123 | 来源:发表于2018-12-12 10:18 被阅读0次

先声明UIButton

UIButton*firstBtn;

  firstBtn = [[UIButton alloc] initWithFrame:CGRectMake(200, 160, 60, 40)];

    [firstBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [firstBtn setTitle:@"60" forState:UIControlStateNormal];

    [firstBtn addTarget:self action:@selector(tagehend) forControlEvents:UIControlEventAllEvents];

    [self.view addSubview:firstBtn];

-(void)tagehend{

    __blockNSIntegertimeOut =59;

    //执行队列

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    //计时器 -》dispatch_source_set_timer自动生成

    dispatch_source_ttimer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);

    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);

    dispatch_source_set_event_handler(timer, ^{

        if(timeOut <=0) {

            dispatch_source_cancel(timer);

            //主线程设置按钮样式-》

            dispatch_async(dispatch_get_main_queue(), ^{

                [self->firstBtnsetTitle:@"发送验证码"forState:UIControlStateNormal];

                [self->firstBtn setUserInteractionEnabled:YES];

            });

        }else{

            //开始计时

            //剩余秒数 seconds

            NSIntegerseconds = timeOut %60;

            NSString*strTime = [NSStringstringWithFormat:@"%.1ld",seconds];

            //主线程设置按钮样式

            dispatch_async(dispatch_get_main_queue(), ^{

                [UIViewbeginAnimations:nilcontext:nil];

                [UIViewsetAnimationDuration:1.0];

                [self->firstBtn setTitle:[NSString stringWithFormat:@"%@",strTime] forState:UIControlStateNormal];

                [UIViewcommitAnimations];

                //计时器件不允许点击

                [self->firstBtn setUserInteractionEnabled:NO];

            });

            timeOut--;

        }

    });

    dispatch_resume(timer);

}

相关文章

网友评论

      本文标题:ios 短信按钮倒计时

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