创建一个简单的倒计时屏幕

时间:2014-05-05 10:53:25

标签: objective-c counter uitabbar

我有一个基于UITabBar的应用程序,其中第一个屏幕应显示特殊事件的倒计时。

我在堆栈溢出和google搜索中看到的大多数代码示例似乎都在viewDidLoad方法中实现了计数器,这在切换到另一个视图控制器时似乎是计数器运行。

计数器机制的正确实现是什么?

我目前的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    _targetDateString = @"09-07-2014";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];

    _targetDate = [[NSDate alloc] init];
    _targetDate = [dateFormatter dateFromString:_targetDateString];

    NSDate *now = [NSDate date];
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *componentsDaysDiff = [gregorianCalendar components:NSDayCalendarUnit fromDate:now toDate:_targetDate options:0];

    if (componentsDaysDiff.day > 0)
    {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats:YES];
    }
}

-(void)updateCountdown
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];

    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [dateFormatter dateFromString:_targetDateString];

    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *componentsHours = [calendar components:NSHourCalendarUnit fromDate:now];
    NSDateComponents *componentMint = [calendar components:NSMinuteCalendarUnit fromDate:now];
    NSDateComponents *componentSec = [calendar components:NSSecondCalendarUnit fromDate:now];

    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *componentsDayDiff = [gregorianCalendar components:NSDayCalendarUnit
                                                               fromDate:now
                                                                 toDate:dateFromString
                                                                options:0];

    NSLog(@"days: %02d, %02d hours, %02d minutes and %02d seconds", componentsDayDiff.day, componentsHours.hour, componentMint.minute, componentSec.second);
}

1 个答案:

答案 0 :(得分:1)

我不确定我是否完全理解您希望计时器执行的操作,但如果您希望计时器仅在查看特定视图时启动和停止,您将需要在- (void) viewDidAppear中启动计时器呼叫[timer fire]并通过调用- (void) viewWillDisappear

[timer invalidate]中将其停止