NSTimer 天数倒计时并发送到标签

NSTimer days countdown and sending to label

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

在用户默认值中存储定时器到期日。您可以在 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);

答案是这样的:

    - (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];