2012-02-13 3 views
5

어떻게이 코드를 변경할 수 있습니다NSTimer를 HH : MM : SS로 사용 하시겠습니까? MM : 그것은 HH을 가지고 있도록

, SS (시, 분, 초를 그리고 난 그래서 난 알려진 .H이나하는 .m에 코드를 추가해야 할 경우 당신은 말해 줄 수있는 하나의

순간

그것은 내가 당신을 감사

을 무슨 뜻인지 알고, 그래서

안녕하세요 사람은 그냥 아마추어의 미끼 복사 할 과거 해요 당신이 알고 있도록 4 등, 3, 2, 1처럼 간다

종류 감사합니다

.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

+0

가능한 복제본 [NSTimer - 스톱워치] (http://stackoverflow.com/questions/3180899/nstimer-stopwatch) – Caleb

+0

NSdate는 어디에 두어야합니까 ?? NSTimer를 모두 교체합니까? –

답변

7

먼저, 다음과 같이 당신의 FirstViewController.hbaseDate 변수를 선언 :

@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]; 
} 

이 또한주의, 당신은 간격을 변경해야 할 것 값을 입력하십시오. 그렇지 않으면 레이블이 1 초에 한 번만 업데이트됩니다.

+0

안녕하세요 당신이 위의 코드에서 위의 코드를 추가 할 수 있습니까? 변수를 기반으로 선언하시오 ???? –

+0

당신은 어느 단계를 이해하기가 어렵습니까? – lawicko

+0

어디 복습 내가 baseDate 넣어 = [NSDate 날짜]; 내 코드에서 - (void) showActivity { NSTimeInterval interval = [baseDate timeIntervalSinceNow]; NSUInteger 초 = ABS ((정수) 간격); NSUInteger 분 = 초/60; NSUInteger 시간 = 분/60; time.text = [NSString stringWithFormat : @ "% 02d : % 02d : % 02d", 시간, 분 % 60, 초 % 60]; } –