您的位置:首页 > 移动开发 > IOS开发

iOS实现倒计时显示 时 分 秒

2017-08-15 17:12 120 查看
1.创建一个类继承自UILabel.(用来显示 时 分 秒)

.h文件

//
// TimeLable.h
// timer
//
// Created by limin on 17/8/15.
// Copyright © 2017年 none. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface TimeLable : UILabel
@property (nonatomic,assign)NSInteger second;
@property (nonatomic,assign)NSInteger minute;
@property (nonatomic,assign)NSInteger hour;
@end.m文件
//
// TimeLable.m
// timer
//
// Created by limin on 17/8/15.
// Copyright © 2017年 none. All rights reserved.
//

#import "TimeLable.h"
@interface TimeLable ()
@property (nonatomic, strong)NSTimer *timer;
@end
@implementation TimeLable

- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.textAlignment = NSTextAlignmentCenter;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeHeadle) userInfo:nil repeats:YES];
}
return self;
}

- (void)timeHeadle{

self.second--;
if (self.second==-1) {
self.second=59;
self.minute--;
if (self.minute==-1) {
self.minute=59;
self.hour--;
}
}
if (self.hour>0) {
self.text = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld",(long)self.hour,(long)self.minute,(long)self.second];
}else if (self.hour==0) {
self.text = [NSString stringWithFormat:@"%.2ld:%.2ld",(long)self.minute,(long)self.second];
}else if (self.minute==0)
{
self.text = [NSString stringWithFormat:@"%.2ld",(long)self.second];
}

if (self.second==0 && self.minute==0 && self.hour==0) {
[self.timer invalidate];
self.timer = nil;
}
}

@end
2.在需要倒计时器的类中导入头文件即可使用,示例:
#import "TimeLable.h"
- (void)viewDidLoad {
[super viewDidLoad];
TimeLable *lable = [[TimeLable alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
lable.hour = 10;
lable.minute = 1;
lable.second = 00;
[self.view addSubview:lable];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: