发送手机验证码按钮

    xiaoxiao2021-08-27  217

    实现思路: 1. 创建按钮, 添加点击方法; 2. 用定时器, 每秒执行一次, 定时改变Button的title,改变Button的样式, 设置Button不可点击; 3. 若倒计时结束, 定时器关闭, 并改变Button的样式, 可以点击

    定时器的选择:NSTime的精度比较低会受到 runloop 影响;dispatch_source_t 的精度较高,dispatch_source_t相关一片博客http://www.cnblogs.com/zhw511006/archive/2012/04/06/2434714.html

    下面是倒计时按钮的类,可以直接使用 .h 文件 @interface YTTimeButton : UIButton

    /** 倒计时按钮

    @param time 倒计时开始的时间 (最大计时为60) @param title 倒计时按钮的文字 @param sColor 倒计时中的字体颜色 @param fColor 倒计时结束的字体颜色 */

    (void)beginTime:(NSInteger)time title:(NSString )title sendingColor:(UIColor )sColor finishColor:(UIColor *)fColor; @end

    import “YTTimeButton.h”

    @implementation YTTimeButton

    (instancetype)init{ self = [super init]; if (self) { } return self; }

    (void)beginTime:(NSInteger)time title:(NSString )title sendingColor:(UIColor )sColor finishColor:(UIColor *)fColor{ __block NSInteger time1 = time -1; 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_TIME_NOW, 1 * NSEC_PER_SEC, 60 * NSEC_PER_SEC); dispatch_source_set_event_handler(timer, ^{

    if (time1 <= 0) { dispatch_source_cancel(timer);//取消定时器 // 时间结束处理 dispatch_async(dispatch_get_main_queue(), ^{ [self setTitle:title forState:UIControlStateNormal]; [self setTitleColor:fColor forState:UIControlStateNormal]; self.userInteractionEnabled = YES; }); }else{ // 倒计时处理 int seconds = time1 % 60; dispatch_async(dispatch_get_main_queue(), ^{ [self setTitle:[NSString stringWithFormat:@"%.2d%@",seconds,title] forState:UIControlStateNormal]; [self setTitleColor:sColor forState:UIControlStateNormal]; self.userInteractionEnabled = NO; }); time1--; }

    }); dispatch_resume(timer);

    } @end

    转载请注明原文地址: https://ju.6miu.com/read-677228.html

    最新回复(0)