NSTimer天倒计时和发送到标签
问题描述:
我有一个按钮触发NSTimer倒计时3天。如何在tableviewCell中显示剩余2天或0天的标签。并且我还想在剩下0天时用红色对单元格着色。并在单元格中有一个按钮来重置计时器另外3天。 Objective-C的。提前致谢!NSTimer天倒计时和发送到标签
答
在用户默认值中存储定时器过期日期。这可以通过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];
不要使用'NSUserDefaults'作为一个全局变量。有些日子是23或25个小时。 – Willeke
Thx很多@voltae!它适用于下面的一些修改。在它显示我未来的日期应该过期之前,但我希望看到只有几天的倒计时。 –