我的ios :label倒计时显示

整个label内部倒计时所显示的内容可以看做一个字符串

头部代码
#import "YQHomeViewController.h"

@interface YQHomeViewController ()

//将sb中的label进行拖拽过来
@property (weak, nonatomic) IBOutlet UILabel *timeLbl;

//创建定时器(因为下面两个方法都使用,所以定时器拿出来设置为一个属性)
@property(nonatomic,strong)NSTimer*countDownTimer;

@end


@implementation YQHomeViewController

//倒计时总的秒数
static NSInteger  secondsCountDown = 86400;

- (void)viewDidLoad {
   [super viewDidLoad];


实现步骤:

1.设置定时器(给定24小时)

一个定时器,定时器里面做设置间隔多少时间执行什么方法(countDownAction)

- (void)viewDidLoad {
    [super viewDidLoad];
 
    //设置定时器
   _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
    //启动倒计时后会每秒钟调用一次方法 countDownAction
   
    //设置倒计时显示的时间
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",secondsCountDown/3600];//时
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(secondsCountDown%3600)/60];//分
    NSString *str_second = [NSString stringWithFormat:@"%02ld",secondsCountDown%60];//秒
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    self.timeLbl.text = [NSString stringWithFormat:@"倒计时   %@",format_time];
    //设置文字颜色
    self.timeLbl.textColor = [UIColor  blackColor ];
    [self.view addSubview:_timeLbl];
    
}

2.方法(countDownAction)(来自创建定时器时需要执行的方法)内部:总秒数递减

1.先递减
2.给时分秒字符串通过递减过后的秒数,重新计算数值,并输出显示

//实现倒计时动作
-(void)countDownAction{
    //倒计时-1
    secondsCountDown--;

    //重新计算 时/分/秒
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",secondsCountDown/3600];
  
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(secondsCountDown%3600)/60];
  
    NSString *str_second = [NSString stringWithFormat:@"%02ld",secondsCountDown%60];
   
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    //修改倒计时标签及显示内容
    self.timeLbl.text=[NSString stringWithFormat:@"实训倒计时   %@",format_time];
   
    
    //当倒计时到0时做需要的操作,比如验证码过期不能提交
    if(secondsCountDown==0){
        
        [_countDownTimer invalidate];
    }
    
    }

屏幕输出结果:

程序输出结果:灰色的两个scrollView可以忽略,不要让它干扰到你
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,951评论 19 139
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,167评论 6 13
  • 8086汇编 本笔记是笔者观看小甲鱼老师(鱼C论坛)《零基础入门学习汇编语言》系列视频的笔记,在此感谢他和像他一样...
    Gibbs基阅读 37,391评论 8 114
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,237评论 2 33
  • 印度教圣典《迦托·奥义书》:悟道之途艰辛困难,如同跨越锋利的剃刀。 “活着到底是为了什么,人生究竟有没有意义,还是...
    雅楠原创阅读 533评论 0 1