发送手机验证码按钮

实现思路:
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值