iOS实现毫秒倒计时的方法详解
发布时间 - 2026-01-11 00:47:31 点击率:次前言

大家应该都知道在app开发中,当展示限时优惠的某些商品时,往往会加一个倒计时,提示用户该商品限时优惠所剩的时间,。那对于开发者来说,这就需要我们去实现的是一个倒计时的功能,这个倒计时根据具体需求,可以以天、小时、分、秒、毫秒作单位。
今天呢,主要说说毫秒计时器。我们知道秒和毫秒之间的进制是1000,也就是说1秒=1000毫秒,那我们做毫秒倒计时器的时候是设置一个时间间隔为1毫秒的计时器,逐一减少毫秒数。但是这样的话太耗时了,所以很多的毫秒计时器中的毫秒数只是0-9之间的数字,这就意味着,这个毫秒计时器的时间间隔是100毫秒,这样相比起1毫秒为间隔的计时器,其消耗就少了很多,同时也达到毫秒计时的效果。
那对于整个毫秒倒计时的实现思路就是:得到未来某个日期的时间戳和当前日期的时间戳,计算这两者之间的时间差,然后设置一个时间间隔为100毫秒的计时器,每隔100毫秒,更新一下倒计时器上相应的数值。
实现方法
自定义一个UIview,将倒计时封装起来。
一、在MsecCountDownView.h中增加时间戳和计时器这两属性
@interface MsecCountDownView : UIView @property(nonatomic, assign)double timeInterval;//未来某个日期的时间戳 @property(nonatomic, strong)NSTimer *timer ; //定时器 @end
二、在MsecCountDownView.m实现相关UI及倒计时方法
@interface MsecCountDownView (){
UIView *countdownBackView;
CGFloat _passTime;
}
@property(nonatomic, strong)UILabel *tipLabel;
@property(nonatomic, strong)UILabel *hoursLabel;
@property(nonatomic, strong)UILabel *minutesLabel;
@property(nonatomic, strong)UILabel *secondsLabel;
@property(nonatomic, strong)UILabel *millionSecondsLabel;
@property(nonatomic, strong)UILabel *label1;
@property(nonatomic, strong)UILabel *label2;
@property(nonatomic, strong)UILabel *label3;
@property(nonatomic, strong)UILabel *label4;
@end
创建相关UI
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
countdownBackView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
[self addSubview:countdownBackView];
_tipLabel=[[UILabel alloc] init];
_tipLabel.frame = CGRectMake(0, 0, 40, countdownBackView.frame.size.height);
[countdownBackView addSubview:_tipLabel];
_tipLabel.font = [UIFont systemFontOfSize:12];
//小时
_hoursLabel=[[UILabel alloc] initWithFrame:CGRectMake(_tipLabel.frame.origin.x+_tipLabel.frame.size.width, 0, 35, countdownBackView.frame.size.height)];
[countdownBackView addSubview:_hoursLabel];
_hoursLabel.font = [UIFont systemFontOfSize:11];
_label1=[[UILabel alloc] initWithFrame:CGRectMake(_hoursLabel.frame.origin.x+_hoursLabel.frame.size.width, _hoursLabel.frame.origin.y, 8, countdownBackView.frame.size.height)];
[countdownBackView addSubview:_label1];
//分钟
_minutesLabel=[[UILabel alloc] initWithFrame:CGRectMake(_label1.frame.origin.x+_label1.frame.size.width, _hoursLabel.frame.origin.y, 20, countdownBackView.frame.size.height)];
[countdownBackView addSubview:_minutesLabel];
_minutesLabel.font = [UIFont systemFontOfSize:11];
_label2=[[UILabel alloc] initWithFrame:CGRectMake(_minutesLabel.frame.origin.x+_minutesLabel.frame.size.width, _hoursLabel.frame.origin.y, 8, countdownBackView.frame.size.height)];
[countdownBackView addSubview:_label2];
//秒
_secondsLabel=[[UILabel alloc] initWithFrame:CGRectMake(_label2.frame.origin.x+_label2.frame.size.width, _hoursLabel.frame.origin.y, 20 , countdownBackView.frame.size.height)];
[countdownBackView addSubview:_secondsLabel];
_secondsLabel.font = [UIFont systemFontOfSize:11];
_label3=[[UILabel alloc] initWithFrame:CGRectMake(_secondsLabel.frame.origin.x+_secondsLabel.frame.size.width, _hoursLabel.frame.origin.y, 8 , countdownBackView.frame.size.height)];
[countdownBackView addSubview:_label3];
_millionSecondsLabel=[[UILabel alloc] initWithFrame:CGRectMake(_label3.frame.origin.x+_label3.frame.size.width, _hoursLabel.frame.origin.y, 20, countdownBackView.frame.size.height)];
[countdownBackView addSubview:_millionSecondsLabel];
//毫秒
_millionSecondsLabel.font = [UIFont systemFontOfSize:11];
_label1.textAlignment=1;
_label2.textAlignment=1;
_label3.textAlignment = 1;
_hoursLabel.textAlignment=1;
_minutesLabel.textAlignment=1;
_secondsLabel.textAlignment=1;
_millionSecondsLabel.textAlignment=1;
_passTime=0.0;
}
return self;
}
生成一个计时器
//得到未来某个日期的时间戳,与当前时间戳相比,得到两者的时间差,生成定时器
- (void)setTimeInterval:(double)timeInterval
{
_timeInterval = timeInterval ;
NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
dataFormatter.dateFormat = @"MM/dd/yyyy HH:mm:ss.SSS";
//获取当前系统的时间,并用相应的格式转换
[dataFormatter stringFromDate:[NSDate date]];
NSString *currentDayStr = [dataFormatter stringFromDate:[NSDate date]];
NSDate *currentDate = [dataFormatter dateFromString:currentDayStr];
//优惠结束的时间,也用相同的格式去转换
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval/1000.0];
NSString *deadlineStr = [dataFormatter stringFromDate:date];
NSDate *deadlineDate = [dataFormatter dateFromString:deadlineStr];
_timeInterval=[deadlineDate timeIntervalSinceDate:currentDate]*1000;
if (_timeInterval!=0)
{
//时间间隔是100毫秒,也就是0.1秒
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:UITrackingRunLoopMode];
}else{
[countdownBackView removeFromSuperview];
}
}
实现每隔100毫秒执行的方法,更新倒计时器上面相应的数值
// 每间隔100毫秒定时器触发执行该方法
- (void)timerAction
{
[self getTimeFromTimeInterval:_timeInterval] ;
// 当时间间隔为0时干掉定时器
if (_timeInterval-_passTime == 0)
{
[_timer invalidate] ;
_timer = nil ;
}
}
// 通过时间间隔计算具体时间(小时,分,秒,毫秒)
- (void)getTimeFromTimeInterval : (double)timeInterval
{
//1s=1000毫秒
_passTime += 100.f;//毫秒数从0-9,所以每次过去100毫秒
_tipLabel.text=@"还剩:";
_label3.text=@".";
_label2.text=@":";
_label1.text=@":";
//小时数
NSString *hours = [NSString stringWithFormat:@"%ld", (NSInteger)((timeInterval-_passTime)/1000/60/60)];
//分钟数
NSString *minute = [NSString stringWithFormat:@"%ld", (NSInteger)((timeInterval-_passTime)/1000/60)%60];
//秒数
NSString *second = [NSString stringWithFormat:@"%ld", ((NSInteger)(timeInterval-_passTime))/1000%60];
//毫秒数
CGFloat sss = ((NSInteger)((timeInterval - _passTime)))%1000/100;
NSString *ss = [NSString stringWithFormat:@"%.lf", sss];
if (minute.integerValue < 10) {
minute = [NSString stringWithFormat:@"0%@", minute];
}
self.hoursLabel.text = [NSString stringWithFormat:@"%@",hours];
self.minutesLabel.text = [NSString stringWithFormat:@"%@",minute];
self.secondsLabel.text = [NSString stringWithFormat:@"%@",second];
self.millionSecondsLabel.text = [NSString stringWithFormat:@"%@",ss];
if (timeInterval - _passTime <= 0) {
[countdownBackView removeFromSuperview];
[self removeFromSuperview];
}
}
三、在ViewController.m给倒计时器赋值,实现自己想要的倒计时
- (void)viewDidLoad {
[super viewDidLoad];
msecView=[[MsecCountDownView alloc] initWithFrame:CGRectMake(50, 100, self.view.frame.size.width-100, 16)];
[self.view addSubview:msecView];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
NSDate* date = [formatter dateFromString:@"2017-04-11 15:10:00.000"];
//将日期转换成时间戳
NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue]*1000;
msecView.timeInterval=timeSp;
}
这样就实现倒计时的功能了。但是使用倒计时还需要注意一点,当离开该页面的时候,记得把定时器暂停,等回到该页面的时候再启动倒计时。
这个可以通过以下两方法实现。
-(void)viewWillAppear:(BOOL)animated{
// 页面出现时,开启计时器
[msecView.timer setFireDate:[NSDate distantPast]];
}
-(void)viewWillDisappear:(BOOL)animated{
// 页面消失时,暂停提示器
[msecView.timer setFireDate:[NSDate distantFuture]];
}
如有需要,可通过下面两种方法下载demo
一:GitHub上下载
二:本地下载
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。
# ios
# 倒计时显示毫秒
# 倒计时
# 分秒毫秒
# 倒计时毫秒2位数
# IOS开发代码分享之用nstimer实现倒计时功能
# IOS实现验证码倒计时功能(一)
# IOS关于大型网站抢购、距活动结束
# 剩余时间倒计时的实现代码
# ios 实现倒计时的两种方式
# iOS中实现简单易懂秒杀倒计时/倒计时代码
# iOS中让多个cell上都出现倒计时的分析与实现
# iOS获取短信验证码倒计时的两种实现方法
# iOS启动页倒计时跳过按钮功能
# Swift实现iOS应用中短信验证码倒计时功能的实例分享
# iOS实现秒杀活动倒计时
# 计时器
# 这就
# 未来
# 每隔
# 的是
# 本地下载
# 如有
# 两种
# 可以通过
# 要注意
# 少了
# 自定义
# 这篇文章
# 现时
# 谢谢大家
# 可通过
# 转换成
# 往往会
# 还需
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
西安市网站制作公司,哪个相亲网站比较好?西安比较好的相亲网站?
如何获取上海专业网站定制建站电话?
公司网站制作价格怎么算,公司办个官网需要多少钱?
Laravel怎么使用Markdown渲染文档_Laravel将Markdown内容转HTML页面展示【实战】
如何在云虚拟主机上快速搭建个人网站?
iOS UIView常见属性方法小结
如何正确下载安装西数主机建站助手?
Laravel的辅助函数有哪些_Laravel常用Helpers函数提高开发效率
Win11怎么更改系统语言为中文_Windows11安装语言包并设为显示语言
原生JS实现图片轮播切换效果
在centOS 7安装mysql 5.7的详细教程
如何在新浪SAE免费搭建个人博客?
如何在云服务器上快速搭建个人网站?
如何自定义建站之星网站的导航菜单样式?
如何在建站之星网店版论坛获取技术支持?
EditPlus中的正则表达式 实战(4)
Win11应用商店下载慢怎么办 Win11更改DNS提速下载【修复】
微信小程序 require机制详解及实例代码
jQuery 常见小例汇总
原生JS获取元素集合的子元素宽度实例
uc浏览器二维码扫描入口_uc浏览器扫码功能使用地址
教学论文网站制作软件有哪些,写论文用什么软件
?
高性能网站服务器部署指南:稳定运行与安全配置优化方案
Laravel怎么实现支付功能_Laravel集成支付宝微信支付
香港服务器网站测试全流程:性能评估、SEO加载与移动适配优化
nodejs redis 发布订阅机制封装实现方法及实例代码
Laravel怎么实现搜索功能_Laravel使用Eloquent实现模糊查询与多条件搜索【实例】
Laravel如何实现一对一模型关联?(Eloquent示例)
javascript中的数组方法有哪些_如何利用数组方法简化数据处理
UC浏览器如何切换小说阅读源_UC浏览器阅读源切换【方法】
Laravel如何监控和管理失败的队列任务_Laravel失败任务处理与监控
谷歌Google入口永久地址_Google搜索引擎官网首页永久入口
谷歌浏览器下载文件时中断怎么办 Google Chrome下载管理修复
网站建设要注意的标准 促进网站用户好感度!
Linux网络带宽限制_tc配置实践解析【教程】
如何快速上传建站程序避免常见错误?
Laravel如何生成和使用数据填充?(Seeder和Factory示例)
微信小程序 wx.uploadFile无法上传解决办法
UC浏览器如何设置启动页 UC浏览器启动页设置方法
大连企业网站制作公司,大连2025企业社保缴费网上缴费流程?
Laravel如何处理JSON字段_Eloquent原生JSON字段类型操作教程
php485函数参数是什么意思_php485各参数详细说明【介绍】
Laravel如何配置和使用缓存?(Redis代码示例)
html5audio标签播放结束怎么触发事件_onended回调方法【教程】
Bootstrap整体框架之CSS12栅格系统
如何在阿里云香港服务器快速搭建网站?
香港服务器如何优化才能显著提升网站加载速度?
C++时间戳转换成日期时间的步骤和示例代码
WEB开发之注册页面验证码倒计时代码的实现
Laravel如何使用Laravel Vite编译前端_Laravel10以上版本前端静态资源管理【教程】

