项目需要实现一个类似于这样的毫秒计时器功能,原来想着用:毫秒 -> 秒 -> 分钟,分用三个控件,后来做个优化一个控件搞定,简单记录一下。
- API调用
[_timer setFireDate:[NSDate date]];
[_timer setFireDate:[NSDate distantFuture]];
- 具体代码实现
@interface ViewController () {
NSInteger _minute; // 分钟
NSInteger _second; // 秒
NSInteger _millisecond; // 毫秒
BOOL _isStop;
}
@property (nonatomic, strong) NSTimer *timer;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_isStop = YES;
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01
target:self
selector:@selector(startTimer)
userInfo:nil
repeats:YES];
// 让定时器暂停
[_timer setFireDate:[NSDate distantFuture]];
}
- (void)startTimer{
_millisecond ++;
if(_millisecond == 100){
_second ++;
_millisecond = 0;
}
if (_second == 60) {
_minute ++;
_second = 0;
}
self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld:%02ld", _minute, _second, _millisecond];
}
// 开始/停止
- (IBAction)start:(id)sender {
UIButton *btn = (UIButton *)sender;
if (_isStop) {
[btn setTitle:@"停止" forState:UIControlStateNormal];
[_timer setFireDate:[NSDate date]];
_isStop = NO;
} else {
[btn setTitle:@"开始" forState:UIControlStateNormal];
[_timer setFireDate:[NSDate distantFuture]];
_isStop = YES;
}
}
// 重置
- (IBAction)reset:(id)sender {
_millisecond = 0;
_second = 0;
_minute = 0;
self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld:%02ld", _millisecond, _second, _minute];
}
@end
网友评论