2012-02-13 48 views
5

我怎樣才能改變這種代碼,以便它有HH:MM:SS(小時,分,秒,對HH:MM:SS使用NSTimer?

,你可以告訴我,如果我需要在.H或.M,所以我知道添加代碼,其中一個

此刻它會像1,2,3,4等

嗨,大家好,只想讓你知道我是一個業餘的誘餌,你會複製過去,所以我知道你的意思,感謝

類別關注

保羅

.H

@interface FirstViewController : UIViewController { 

    IBOutlet UILabel *time; 

    NSTimer *myticker; 

    //declare baseDate 
    NSDate* baseDate; 

} 

-(IBAction)stop; 
-(IBAction)reset; 

@end 

.M

#import "FirstViewController.h" 

@implementation FirstViewController 

-(IBAction)start { 
    [myticker invalidate]; 
    baseDate = [NSDate date]; 
    myticker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES]; 
} 

-(IBAction)stop;{ 

    [myticker invalidate]; 
    myticker = nil; 
} 
-(IBAction)reset;{ 

    time.text = @"00:00:00"; 
} 
-(void)showActivity { 
    NSTimeInterval interval = [baseDate timeIntervalSinceNow]; 
    NSUInteger seconds = ABS((int)interval); 
    NSUInteger minutes = seconds/60; 
    NSUInteger hours = minutes/60; 
    time.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes%60, seconds%60]; 
} 
+0

如果你想測量時間,我建議你使用NSDate類而不是增加一些任意的整數變量。 – lawicko 2012-02-13 10:45:04

+0

[NSTimer - Stopwatch]可能的重複(http://stackoverflow.com/questions/3180899/nstimer-stopwatch) – Caleb 2012-02-13 11:19:34

+0

我在哪裏把NSdate?我是否替換了所有的NSTimer? – 2012-02-13 12:40:14

回答

7

首先,聲明baseDate變量在FirstViewController.h,像這樣:

@interface FirstViewController : UIViewController { 

    IBOutlet UILabel *time; 

    NSTimer *myticker; 

    //declare baseDate 
    NSDate* baseDate; 
} 

然後,在FirstViewControl的ler.m啓動方法添加baseDate = [NSDate date]這樣的:

-(IBAction)start { 
    [myticker invalidate]; 
    baseDate = [NSDate date]; 
    myticker = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(showActivity) userInfo:nil repeats:YES]; 
} 

之後,改變你的showActivity方法是這樣的:

-(void)showActivity { 
    NSTimeInterval interval = [baseDate timeIntervalSinceNow]; 
    double intpart; 
    double fractional = modf(interval, &intpart); 
    NSUInteger hundredth = ABS((int)(fractional*100)); 
    NSUInteger seconds = ABS((int)interval); 
    NSUInteger minutes = seconds/60; 
    NSUInteger hours = minutes/60; 
    time.text = [NSString stringWithFormat:@"%02d:%02d:%02d:%02d", hours, minutes%60, seconds%60, hundredth]; 
} 

還要注意,你將不得不更改間隔值爲您的計時器,否則您的標籤將只更新一次。

+0

嗨,你可以將它添加到我的代碼上面,因爲我發現這很難理解?聲明基於變量?謝謝 – 2012-02-13 13:57:45

+0

你覺得哪一步很難理解? – lawicko 2012-02-13 14:00:01

+0

在哪裏比較,我把baseDate = [NSDate日期];在我的代碼和 - (void)showActivity {NSTimeInterval interval = [baseDate timeIntervalSinceNow]; NSUInteger seconds = ABS((int)interval); NSUInteger分鐘=秒/ 60; NSUInteger小時=分鐘/ 60; time.text = [NSString stringWithFormat:@「%02d:%02d:%02d」,hours,minutes%60,seconds%60]; } – 2012-02-13 14:01:14