美文网首页
iOS 开发 毫秒计时器

iOS 开发 毫秒计时器

作者: 强子ly | 来源:发表于2019-06-15 13:01 被阅读0次
    毫秒计时器.gif

    项目需要实现一个类似于这样的毫秒计时器功能,原来想着用:毫秒 -> 秒 -> 分钟,分用三个控件,后来做个优化一个控件搞定,简单记录一下。


    • API调用
    [_timer setFireDate:[NSDate date]];
    [_timer setFireDate:[NSDate distantFuture]];
    
    • 具体代码实现
    7B4B4EB592A1B625E540262208B6AF0D.jpg
    @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
    

    相关文章

      网友评论

          本文标题:iOS 开发 毫秒计时器

          本文链接:https://www.haomeiwen.com/subject/clcbfctx.html