【问题标题】:Making a countdown to a time every day每天倒计时
【发布时间】:2013-11-10 22:14:52
【问题描述】:

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

我的视图控制器.h

@interface ViewController : UIViewController {

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

}

@end

我的视图控制器.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];
}

【问题讨论】:

  • 这与您使用 Xcode 5 有什么关系?如果您使用emacsmake 来编译和部署您的应用程序,问题会有所不同吗?我猜没有。

标签: ios nsdate nstimer


【解决方案1】:

当您最终到达您想要的日期和时间时,您可以启动一个新计时器(并终止旧计时器),或者只更新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];
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多