10

我想从当前时间倒计时到特定日期并在标签中显示该值。我查看了一些 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 中一无所获。

4

4 回答 4

19

使用此答案中的代码(复制粘贴在下面以确保示例的完整性)来获取倒计时期间的各个组成部分:

- (void)updateCountdown {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *startingDate = [dateFormatter dateFromString:@"2005-01-01"];
    NSDate *endingDate = [NSDate date];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:startingDate toDate:endingDate 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 Years %d Months %d Days %d Hours %d Minutes %d Seconds", days, months, years, hours, minutes, seconds];
    cell.myLabel.text = countdownText;

然后,我们可以使用performSelector:withObject:afterDelay:使该方法在指定的延迟后再次被调用(注意延迟以秒为单位):

    [self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1];
}
于 2013-05-20T08:25:01.877 回答
2

声明成员变量,如 NSDate *startDate,*EndDate; 无符号长计数;

根据您的要求

-(void)setUpCountDown{
    startDate = [NSDate date]; //Current time
    NSDate *endDate = [startDate dateByAddingTimeInterval:10000]; //some future date
    NSTimeInterval milliseconds = [endDate timeIntervalSinceDate:startDate];/////will give time in milliseconds
    countDownSeconds = (unsigned long)milliseconds/1000;
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:nil repeats:YES];
}

-(void)countDown:(NSTimer *)timer{
    if (countDownSeconds<=0) {
        [timer invalidate];
        timer = nil;
    }
    NSLog(@"Time Elapsed in seconds %d", countDownSeconds);
    countDownSeconds--;
}
于 2013-05-20T09:48:47.330 回答
1
let formatter = NSDateFormatter()
let userCalendar = NSCalendar.currentCalendar()
let requestedComponent: NSCalendarUnit = [
    //NSCalendarUnit.Month,
    //NSCalendarUnit.Day,
    NSCalendarUnit.Hour,
    NSCalendarUnit.Minute,
    NSCalendarUnit.Second

]
func printTime() {
    formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
    let startTime = NSDate()
    let endTime = formatter.dateFromString("12/25/16 8:00:00 a")
    let timeDifference = userCalendar.components(requestedComponent, fromDate: startTime, toDate: endTime!, options: [])
    self.TimeLabel.text = " \(timeDifference.hour)Hours \(timeDifference.minute)Minutes \(timeDifference.second) Seconds"
}

//Put this in your initialiser

let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(myProject.printTime), userInfo: nil, repeats: true)
    timer.fire()

我知道这个线程很老了,但这就是我在 Swift 中的做法

于 2016-07-31T19:53:03.747 回答
0

保留一个实例变量来保存日期

//Fire Timer
_savedDate = [[NSDate date]dateByAddingTimeInterval:30];
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(countDown:) userInfo:nil repeats:YES];

- (void)countDown:(NSTimer *)timer
{
    NSDate *date = [NSDate date];

    if ([date isEqualToDate:_savedDate]) {
        [timer invalidate];
    }

    NSDateComponents *dateComponents = [[NSCalendar currentCalendar]components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:date toDate:_savedDate options:0];
    NSLog(@"%02d:%02d:%02d",dateComponents.hour,dateComponents.minute,dateComponents.second);
}
于 2013-05-20T08:32:41.100 回答