iOS按钮倒计时

创建一个UIButton的类别,其他控件也可以使用这个方法:

/*
 *    倒计时按钮
 *    @param timeLine  倒计时总时间
 *    @param title     还没倒计时的title
 *    @param subTitle  倒计时的子名字 如:时、分
 *    @param mColor    还没倒计时的颜色
 *    @param color     倒计时的颜色
 */

- (void)startWithTime:(NSInteger)timeLine
                title:(NSString *)title
       countDownTitle:(NSString *)subTitle
            mainColor:(UIColor *)mColor
           countColor:(UIColor *)color;
-(void)startWithTime:(NSInteger)timeLine
               title:(NSString *)title
      countDownTitle:(NSString *)subTitle
           mainColor:(UIColor *)mColor
          countColor:(UIColor *)color
{
    //倒计时时间
    __block NSInteger timeOut = timeLine;
    //创建一个线程
    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, ^{
        //小于0时
        if (timeOut <= 0)
        {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.backgroundColor = mColor;
                [self setTitle:title forState:UIControlStateNormal];
                self.userInteractionEnabled = YES;
            });
        }
        else
        {
            //大于0时计算需要显示的文字
            int seconds = (int)timeOut % 60;
            NSString * timeStr = [NSString stringWithFormat:@"%0.2d",seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.backgroundColor = color;
                [self setTitle:[NSString stringWithFormat:@"%@%@",timeStr,subTitle] forState:UIControlStateNormal];
                self.userInteractionEnabled = NO;
            });
            timeOut--;
        }
    });
    dispatch_resume(_timer);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,024评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,198评论 4 61
  • 1. 系统质量 系统质量属性主要有:可用性、可修改性、性能、安全性、可测试性和、易用性。 可用性: 是指系统能够...
    by小杰阅读 785评论 0 0
  • 一场充沛的雨 清透细密 结束了夏所有的炙热与纠缠 微凉的晨风 消散心头久踞的躁郁 从此 我不断仰望高阔的蓝天 映照...
    飞树阅读 175评论 0 0
  • 男神说这部电影让他看到高潮。 我想了想他看片的口味,《贞子》《午夜凶铃》《鬼虐系列》《沉默的羔羊》所有昆丁的电影。...
    六子棋阅读 345评论 2 0