我想从当前时间倒计时到特定日期并在标签中显示该值。我查看了一些 NSTimer 教程,但我不知道如何将它们应用于我的情况。
NSTimeInterval TimeInterval = [aString doubleValue];
NSDate* upperDate = [aDate dateByAddingTimeInterval:TimeInterval];
NSDate* Today = [NSDate date];
//cell.myLabel.text = here i should write a countdown.
对不起,代码不足。在这里提问之前,我通常会尝试编写一些自己的代码,但这次我不知道该写什么。
编辑 所以有了 PartiallyFinite 的答案,我想出了我是如何设置计时器的。但是因为我使用的是 tableview,所以我无法为 MyTimerLabel 实现重复消息。这是我刚刚做的:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"MyCell";
MekanListesiViewCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
aClass *aC = [myArray objectAtIndex:indexPath.row];
NSTimeInterval TimeInterval = [aC.aTimeIntervalwithString doubleValue];
NSDate* UpperDate = [aC.aNSDate dateByAddingTimeInterval:TimeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:[NSDate date] toDate:UpperDate options:0];
NSInteger days = [dateComponents day];
NSInteger months = [dateComponents month];
NSInteger years = [dateComponents year];
NSInteger hours = [dateComponents hour];
NSInteger minutes = [dateComponents minute];
NSInteger seconds = [dateComponents second];
NSString *countdownText = [NSString stringWithFormat:@"%d Days %d:%d:%d", days, hours, minutes, seconds];
cell.countdownText= countdownText;
[self performSelector:@selector(updateCoundown)]; // The delay is in seconds, make it whatever you want.
return cell;
}
At myCellView.h
@interface MekanListesiViewCell : UITableViewCell
@property (nonatomic, weak) IBOutlet UILabel *MyTimerLabel;
@property(weak)NSString *countdownText;
at myCellView.m
-(void)updateCoundown{
MyTimerLabel.text = countdownText;
[self performSelector:@selector(updateCoundown) withObject:nil afterDelay:1];
}
我在 MyTimerLabel 中一无所获。