很多項目中佳励,都會涉及到倒計時的功能, 發(fā)送完驗證碼開始倒計時,針對這個我個人封裝了一個簡單的方法來實現(xiàn)此功能紧帕, 話不多說见秽,上干貨愉烙!
首先我是在UIButton的一個延展類里面添加了一個方法?
/**
*? 倒計時按鈕
*
*? @param timeLine 倒計時總時間
*/
- (void)startCountDownWithTime:(NSInteger)timeLine;
然后在.m中實現(xiàn)
- (void)startCountDownWithTime:(NSInteger)timeLine{
NSString *subTitle = @"重新發(fā)送";
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);
//每秒執(zhí)行一次
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(_timer, ^{
//倒計時結(jié)束,關(guān)閉
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);
}
以上就是全部代碼解取,怎么樣 步责,是不是感覺很簡單呢?
希望可以幫到大家 ~~~~