倒计时略简单,就是NSTimer 的使用,代码如下
@property (nonatomic, assign)int intervalTime;
@property (nonatomic, strong)NSDictionary *dic;
@implementation HNCountdownModel
- (void)setTime:(NSDate *)lastTime
{
self.day = [NSString stringWithFormat:@"%d",self.intervalTime / (24 * 3600) ];
self.hour = [NSString stringWithFormat:@"%d",self.intervalTime % (24 * 3600) /3600];
self.minute = [NSString stringWithFormat:@"%d",self.intervalTime % 3600 / 60 ];
self.second = [NSString stringWithFormat:@"%d",self.intervalTime %60];
self.dic = @{@"day":self.day,@"hour":self.hour,@"minute":self.minute,@"second":self.second};
self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.countDownTimer forMode:NSRunLoopCommonModes];//不理解的同学把这句注释掉看看就行了,总之就是防止计时器计时出现延迟不准等情况,和NSRunLoop有关,以后详聊
}
我们这里利用通知来把数据实时传输出去,或许还可以用KVO,没有仔细研究,研究过的麻烦说声.
- (void)countDown:(NSTimer *)sender
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"countDown" object:nil userInfo:self.dic];
self.intervalTime--;
self.day = [NSString stringWithFormat:@"%d",self.intervalTime / (24 * 3600) ];
self.hour = [NSString stringWithFormat:@"%d",self.intervalTime % (24 * 3600) /3600];
self.minute = [NSString stringWithFormat:@"%d",self.intervalTime % 3600 / 60 ];
self.second = [NSString stringWithFormat:@"%d",self.intervalTime %60];
// NSLog(@"%@-%@-%@-%@",self.day,self.hour,
// self.minute,self.second);
self.dic = @{@"day":self.day, @"hour":self.hour,@"minute":self.minute,@"second":self.second};
if (self.intervalTime == 0) {
NSLog(@"倒计时完成");
[self.countDownTimer invalidate];//暂停计时器
}
}
在VC中注册通知如下
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:@"countDown" object:nil];
#pragma mark - 通知
- (void)notificationAction:(NSNotification *)notify
{
NSLog(@"%@",notify);
self.orderView.dayLB.text = notify.userInfo[@"day"];
self.orderView.houreLB.text = notify.userInfo[@"hour"];
self.orderView.minuteLB.text = notify.userInfo[@"minute"];
self.orderView.secondLB.text = notify.userInfo[@"second"];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"countDown" object:nil];
}
网友评论