1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//
// CountDownLabel.m
// Lighting
//
// Created by 曹云霄 on 2016/12/6.
// Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//
#import "CountDownLabel.h"
@interface CountDownLabel ()
/// 定时器,使用 weak 或者 strong 都行
@property (nonatomic, strong) NSTimer *timer;
/// 剩余天数
@property (nonatomic, assign) NSUInteger day;
/// 剩余小时数
@property (nonatomic, assign) NSUInteger hour;
/// 剩余分钟数
@property (nonatomic, assign) NSUInteger minute;
/// 剩余秒数
@property (nonatomic, assign) NSUInteger second;
@end
@implementation CountDownLabel
/// 根据传入的具体秒数,开始倒计时
- (void)beginCountDownWithTimeInterval:(NSTimeInterval)timerInterval {
[self initTimeParametersWithTimeInterval:timerInterval];
}
/// 通过传入的时间间隔对时间参数进行初始化
- (void)initTimeParametersWithTimeInterval:(NSInteger)interval {
NSUInteger secondPerDay = 24 * 60 * 60;
NSUInteger secondPerHour = 60 * 60;
NSUInteger secondPerMinute = 60;
// 计算天数
self.day = interval / secondPerDay;
// 剩余小时不应该大于24小时,所以应该先除去满足一天的秒数,再计算还剩下多少小时
self.hour = interval % secondPerDay / secondPerHour;
// 剩余分钟数与上面同理
self.minute = interval % secondPerHour / secondPerMinute;
// 剩余秒数直接等于秒数对每分钟秒数所取的余数
self.second = interval % secondPerMinute;
// 更新值
[self updateText];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
/// 时间减一秒方法
- (void)updateTimer {
// 减一秒
self.second--;
// 判断秒数
if (self.second == -1) {
self.second = 59;
self.minute--;
}
// 判断分钟数
if (self.minute == -1) {
self.minute = 59;
self.hour--;
}
// 判断小时数
if (self.hour == -1) {
self.hour = 23;
self.day--;
}
// 判断是否没时间了
if (self.day == 0 && self.hour == 0 && self.minute == 0 && self.second == 0) {
[self.timer invalidate];
if (self.countDownCompleteBlock) {
self.countDownCompleteBlock();
}
}
// 更新值
[self updateText];
}
- (void)updateText {
self.text = [NSString stringWithFormat:@"%02zd:%02zd:%02zd", self.hour, self.minute, self.second];
}
/// 停止定时器
- (void)stopTimer
{
[self.timer invalidate];
}
// best solution
- (void)removeFromSuperview {
[super removeFromSuperview];
[self.timer invalidate];
}
@end