每天倒计时一次

时间:2013-11-10 22:14:52

标签: ios nsdate nstimer

我想要的是一个每天倒数到倒数的应用程序 例如,代码告诉它倒计时到编码到应用程序中的某个时间,并且不能通过用户输入进行更改。 我所拥有的是使其倒计时到特定时间和日期的代码,但这不是每天重复 所以我正在寻找的是今天它将倒数到22:02,明天它也会倒数到22:02。 我试过谷歌,youtube,但无法在任何地方找到它。 我也会添加我的代码,希望你能告诉我哪里出错了。

我的视图controller.h

@interface ViewController : UIViewController {

NSDate *destinationDate;
IBOutlet UILabel *datelabel;
NSTimer *timer;

}

@end

我的观点controller.m

-(void) updateLabel {

NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int units = NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [calender components:units fromDate:[NSDate date] toDate:destinationDate options:0];
[datelabel setText:[NSString stringWithFormat:@"%d%c: %d%c", [components minute], ' ', [components second], ' ']];
}


- (void)viewDidLoad {
[super viewDidLoad];

destinationDate = [NSDate dateWithTimeIntervalSince1970:1384121134];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
}

1 个答案:

答案 0 :(得分:0)

当您最终达到所需的日期和时间时,您可以启动新计时器(并取消旧计时器),或只更新destinationDate。例如,在updateLabel中,您可以这样做:

-(void) updateLabel
{
    NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    int units = NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *components = [calender components:units fromDate:[NSDate date] toDate:destinationDate options:0];
    [datelabel setText:[NSString stringWithFormat:@"%d%c: %d%c", [components minute], ' ', [components second], ' ']];
    if (([components minute] <= 0) && ([components second] <= 0))
    {
        // Set it for again for 24 hours from now - 24 hours * 60 min/hr * 60 secs/min
        destinationDate = [destinationDate dateByAddingTimeInterval:24.0 * 60.0 * 60.0];
    }
}
相关问题