IOS開發(fā)代碼分享之用nstimer實現(xiàn)倒計時功能
更新時間:2014年09月18日 09:26:18 投稿:hebedich
在制作IOS項目中,我們經(jīng)常要用到倒計時功能,今天就分享下使用nstimer實現(xiàn)的倒計時功能的代碼,希望對大家能有所幫助
用nstimer實現(xiàn)倒計時功能,廢話不多說,直接上代碼,詳細解釋請參照注釋
//
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
//
- (void)timerFireMethod:(NSTimer *)theTimer
{
BOOL timeStart = YES;
NSCalendar *cal = [NSCalendar currentCalendar];//定義一個NSCalendar對象
NSDateComponents *endTime = [[NSDateComponents alloc] init]; //初始化目標時間...
NSDate *today = [NSDate date]; //得到當前時間
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateString = [dateFormatter dateFromString:todate];
NSString *overdate = [dateFormatter stringFromDate:dateString];
// NSLog(@"overdate=%@",overdate);
static int year;
static int month;
static int day;
static int hour;
static int minute;
static int second;
if(timeStart) {//從NSDate中取出年月日,時分秒,但是只能取一次
year = [[overdate substringWithRange:NSMakeRange(0, 4)] intValue];
month = [[overdate substringWithRange:NSMakeRange(5, 2)] intValue];
day = [[overdate substringWithRange:NSMakeRange(8, 2)] intValue];
hour = [[overdate substringWithRange:NSMakeRange(11, 2)] intValue];
minute = [[overdate substringWithRange:NSMakeRange(14, 2)] intValue];
second = [[overdate substringWithRange:NSMakeRange(17, 2)] intValue];
timeStart= NO;
}
[endTime setYear:year];
[endTime setMonth:month];
[endTime setDay:day];
[endTime setHour:hour];
[endTime setMinute:minute];
[endTime setSecond:second];
NSDate *overTime = [cal dateFromComponents:endTime]; //把目標時間裝載入date
//用來得到具體的時差,是為了統(tǒng)一成北京時間
unsigned int unitFlags = NSYearCalendarUnit| NSMonthCalendarUnit| NSDayCalendarUnit| NSHourCalendarUnit| NSMinuteCalendarUnit| NSSecondCalendarUnit;
NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:overTime options:0];
NSString *t = [NSString stringWithFormat:@"%d", [d day]];
NSString *h = [NSString stringWithFormat:@"%d", [d hour]];
NSString *fen = [NSString stringWithFormat:@"%d", [d minute]];
if([d minute] < 10) {
fen = [NSString stringWithFormat:@"0%d",[d minute]];
}
NSString *miao = [NSString stringWithFormat:@"%d", [d second]];
if([d second] < 10) {
miao = [NSString stringWithFormat:@"0%d",[d second]];
}
// NSLog(@"===%@天 %@:%@:%@",t,h,fen,miao);
[_longtime setText:[NSString stringWithFormat:@"%@天 %@:%@:%@",t,h,fen,miao]];
if([d second] > 0) {
//計時尚未結束,do_something
// [_longtime setText:[NSString stringWithFormat:@"%@:%@:%@",d,fen,miao]];
} else if([d second] == 0) {
//計時結束 do_something
} else{
//計時器失效
[theTimer invalidate];
}
}
相關文章
iOS9 系統(tǒng)分享調用之UIActivityViewController
UIActivityViewController類是一個標準的view controller,通個使用這個controller,你的應用程序就可以提供各種服務。本文給大家介紹iOS9 系統(tǒng)分享調用之UIActivityViewController,感興趣的朋友一起學習吧2015-11-11

