Just a Computer Graphics Studio & My Life

[iOS] 計時器 (Timer)

想要做一個計時器 (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

參考:Timer / 計時器的基本使用方法使用 Timer / 計時器實做 Pause 與 Resume

Advertisements

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: