歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

iOS開發:用NSTimer實現倒計時

首先定義NSTimer

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];

倒計時在timer的觸發方法裡完成

- (void)timerFireMethod:(NSTimer *)timer

{

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [[NSDateComponents alloc] init];

    [components setYear:2012];

    [components setMonth:8];

    [components setDay:13];

    [components setHour:12];

    [components setMinute:0];

    [components setSecond:0];

    NSDate *fireDate = [calendar dateFromComponents:components];//目標時間

    NSDate *today = [NSDate date];//當前時間

    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

     NSDateComponents *d = [calendar components:unitFlags fromDate:today toDate:fireDate options:0];//計算時間差

    auctionTime.text = [NSString stringWithFormat:@"%d天%d小時%d%分%d秒", [d day], [d hour], [d minute], [d second]];//倒計時顯示

}

這樣就完成了倒計時。

不過如果有專門的服務器時,要把服務器和自己本機的時間差考慮進去

Copyright © Linux教程網 All Rights Reserved