iOS -计数器的实现 计数精度秒

94A653AFBD72D17C839E9ED8A37CCBF8.jpg
-(UILabel *)timeLable{
if(!_timeLable){
_timeLable=[[UILabel alloc]init];
__block NSInteger second = 0;
__block NSInteger min = 0;
__block NSInteger hour = 0;
//全局队列 默认优先级
dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//定时器模式 事件源
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
//_timer = timer;
//NSEC_PER_SEC是秒,*1是每秒
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), NSEC_PER_SEC * 1, 0);
//设置响应dispatch源事件的block,在dispatch源指定的队列上运行
dispatch_source_set_event_handler(timer, ^{
//回调主线程,在主线程中操作UI
dispatch_async(dispatch_get_main_queue(), ^{
if (second >= 0) {
if(second == 60){
second =0;
min++;
if (min == 60) {
min =0;
hour++;
}
}
_timeLable.text = [NSString stringWithFormat:@"正在看房中:%.2ld:%.2ld:%.2ld",hour,min,second];
second++;
}
else
{
//这句话必须写否则会出问题
dispatch_source_cancel(timer);
_timeLable.text = @"正在看房中*****";
}
});
});
//启动源
dispatch_resume(timer);
if (@available(iOS 8.2, *)) {
_timeLable.font = [UIFont systemFontOfSize:18 weight:0.2];
}
[_timeLable setTextColor:[UIColor redColor]];
}
return _timeLable;
}
网友评论