2012-02-13 36 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