想要做一個計時器 (Timer),可以怎麼做?使用NSTimer,每隔一秒鐘更新一次秒數,就這麼簡單!
程式碼一樣簡單利落~
/**
Theme: Timer
IDE: Xcode 5
Language: Objective C
Date: 103/01/18
Author: HappyMan
Blog: https://cg2010studio.wordpress.com/
*/
- (void)viewDidLoad
{
[super viewDidLoad];
// 設定Timer,每過1秒執行方法
self.accumulatedTime = 0;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
}
-(void)updateTime:(NSTimer *)timer
{
self. accumulatedTime++;
NSLog(@"accumulatedTime:%f",self. accumulatedTime);
}
執行結果:
accumulatedTime:1.000000
accumulatedTime:2.000000
accumulatedTime:3.000000
accumulatedTime:4.000000
accumulatedTime:5.000000
accumulatedTime:6.000000
accumulatedTime:7.000000
…
…
若要進一步變成時、分、秒,可以如此做⋯⋯
NSInteger tempHour = self.accumulatedTime / 3600;
NSInteger tempMinute = self.accumulatedTime / 60 - (tempHour * 60);
NSInteger tempSecond = self.accumulatedTime - (tempHour * 3600 + tempMinute * 60);
NSString *hour = [[NSNumber numberWithInteger:tempHour] stringValue];
NSString *minute = [[NSNumber numberWithInteger:tempMinute] stringValue];
NSString *second = [[NSNumber numberWithInteger:tempSecond] stringValue];
if (tempHour < 10) {
hour = [@"0" stringByAppendingString:hour];
}
if (tempMinute < 10) {
minute = [@"0" stringByAppendingString:minute];
}
if (tempSecond < 10) {
second = [@"0" stringByAppendingString:second];
}
self.timeLabel.text = [NSString stringWithFormat:@"%@:%@:%@", hour, minute, second];
執行結果:
01:03:14
隨意留個言吧:)~