按钮倒计时的实现 iOS

很多项目中,都会涉及到倒计时的功能, 发送完验证码开始倒计时,针对这个我个人封装了一个简单的方法来实现此功能, 话不多说,上干货!

首先我是在UIButton的一个延展类里面添加了一个方法 

/**

*  倒计时按钮

*

*  @param timeLine 倒计时总时间

*/

- (void)startCountDownWithTime:(NSInteger)timeLine;

然后在.m中实现

- (void)startCountDownWithTime:(NSInteger)timeLine{

NSString *subTitle = @"重新发送";

UIColor *defultColor = UGUColorFromRGB_0x(0xed145b);

UIColor *runningColor = UGUColorFromRGB_0x(0xd5d5d5);

//倒计时时间

__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, ^{

//倒计时结束,关闭

if (timeOut <= 0) {

dispatch_source_cancel(_timer);

dispatch_async(dispatch_get_main_queue(), ^{

[self setTitle:subTitle forState:UIControlStateNormal];

self.userInteractionEnabled = YES;

self.layer.borderColor = [defultColor CGColor];

[self setTitleColor:defultColor forState:UIControlStateNormal];

});

} else {

self.userInteractionEnabled = YES;

int allTime = (int)timeLine + 1;

int seconds = timeOut % allTime;

NSString *timeStr = [NSString stringWithFormat:@"%0.1d", seconds];

dispatch_async(dispatch_get_main_queue(), ^{

[self setTitle:[NSString stringWithFormat:@"%@%@",timeStr,@"s"] forState:UIControlStateNormal];

self.layer.borderColor = [runningColor CGColor];

[self setTitleColor:runningColor forState:UIControlStateNormal];

self.userInteractionEnabled = NO;

});

timeOut--;

}

});

dispatch_resume(_timer);

}


以上就是全部代码,怎么样 ,是不是感觉很简单呢?

希望可以帮到大家 ~~~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容