-1
我有一個按鈕觸發NSTimer倒計時3天。如何在tableviewCell中顯示剩餘2天或0天的標籤。並且我還想在剩下0天時用紅色對單元格着色。並在單元格中有一個按鈕來重置計時器另外3天。 Objective-C的。提前致謝!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!它適用於下面的一些修改。在它顯示我未來的日期應該過期之前,但我希望看到只有幾天的倒計時。 –