NSTimer天倒计时并发送到标签

时间:2017-04-24 12:13:45

标签: objective-c nstimer countdown

我有一个按钮可以触发NSTimer倒计时3天。如何在tableviewCell中显示剩余2天或剩余0天的标签。我还想在剩下0天时用红色为细胞着色。在单元格中有一个按钮可以将计时器重置另外3天。 Objective-C的。提前谢谢!

2 个答案:

答案 0 :(得分:0)

答案是这样的:

    - (IBAction)In3DaysButton:(id)sender
    {
    NSInteger expiredInDays = 4;

    // Calculate the Date.
    // Get the Date

    NSDate * now = [NSDate date];

    NSTimeInterval  tiNow = [now timeIntervalSinceReferenceDate];
    tiNow = tiNow + 60*60*24*expiredInDays;
    NSDate * expires = [NSDate dateWithTimeIntervalSinceReferenceDate:tiNow];

   NSDateComponents *countdown = [[NSCalendar currentCalendar]
                               components:(NSCalendarUnitDay)
                                          // | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond)
                               fromDate:[NSDate date]
                               toDate:expires
                               options:0];

    NSString *myDays = [NSString stringWithFormat:@"%ld", (long)[countdown day]];

    [[NSUserDefaults standardUserDefaults] setObject:myDays forKey:@"Expired_Date"];

}

然后当我想要它时:

    NSDate *expiredDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"Expired_Date"];
    doItLabel.text = [NSString stringWithFormat:@" f_ck me in %@ day(s)",   expiredDate];

    //And for coloring label I add after

    if ([NSDate date] > expiredDate) doItLabel.textColor = [UIColor redColor];

答案 1 :(得分:-1)

将计时器已过期日存储在“用户默认值”中。您可以在IBAction方法中执行此操作以设置新的过期日期。再次运行此操作会重置该值。

   NSInteger expiredInDays = 3;

// Calculate the Date.
// Get the Date
NSDate * now = [NSDate date];
NSTimeInterval  tiNow = [now timeIntervalSinceReferenceDate];
tiNow = tiNow + 60*60*24*expiredInDays;
NSDate * expires = [NSDate dateWithTimeIntervalSinceReferenceDate:tiNow];
[[NSUserDefaults standardUserDefaults] setObject:expires forKey:@"Expired Date"];

在代码中询问您需要的到期日。

NSDate *expiredDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"Expired Date"];
NSLog(@"Expires in: %@",expiredDate);