2016-11-22 2 views
-1

nstimer을 사용하여 라벨에 카운트 다운 타이머를 표시합니다. 타이머를 시작하고 라벨에 카운트 다운을 표시 할 수 있지만 매초마다 표시되는 것이 아니라 타이머가 다음 초로 점프합니다. 카운트 다운 타이머가 10 초로 설정되면 카운트 다운 타이머 라벨에 9,7,5,3,1 만 표시됩니다.nstimer 카운트 다운이 예상대로 작동하지 않습니다.

아래 코드는 제 코드입니다.

NSTimer *tktTimer; 
int secondsLeft; 


- (void)startTimer { 
    secondsLeft = 10; 
     tktTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES]; 
} 

-(void) updateCountdown { 
    int hours, minutes, seconds; 

    secondsLeft--; 
    NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0 
    hours = secondsLeft/3600; 
    minutes = (secondsLeft % 3600)/60; 
    seconds = (secondsLeft %3600) % 60; 
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds]; 


    if (--secondsLeft == 0) { 
     [tktTimer invalidate]; 
     countDownlabel.text = @"Completed"; 
    } 


} 

도움이 될 것입니다.

답변

3

--secondsLeft 변수를 업데이트합니다. 다음 감소가 0인지 확인하려면 if (secondsLeft - 1 == 0)

각 틱이 변수를 두 번 감소시킵니다. 쉽게 이해할 수있는 코드로 타이머를 수행 할 수

-(void) updateCountdown { 
    int hours, minutes, seconds; 

    secondsLeft--; 
    if (secondsLeft == 0) { 
     [tktTimer invalidate]; 
     countDownlabel.text = @"Completed"; 
     return; 
    }   
    NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0 
    hours = secondsLeft/3600; 
    minutes = (secondsLeft % 3600)/60; 
    seconds = (secondsLeft %3600) % 60; 
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds]; 
} 
+0

만약 내가이 조건을 사용하는 경우 타이머를 무효화하는 문제에 직면하고 있습니다. 타이머를 무효화하기 위해 코드를 표시하여 답변을 편집 할 수 있습니까? – Madhu

+0

코드를 살펴보면 작동 방식이 "0"이 아니라 "1"이됩니다. 0인지 확인하는 것이 좋습니다. 내 대답을 업데이트 할게. – EvilGeniusJamie

-1

// 달콤한 간단한 방법 :

또한,이 0이 아닌 아래는이 처리하는 더 좋은 방법입니다, 1 일에 "완료"텍스트를 트리거

DECLARE

int seconds; 
NSTimer *timer; 

//있는 viewDidLoad 방법에서

seconds=12; 
    timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(GameOver) userInfo:nil repeats:YES ]; 

-(void)GameOver 
{ 
    seconds-=1; 
    lblUpTimer.text=[NSString stringWithFormat:@"%d",seconds];//shows counter in label 

if(seconds==0) 
[timer invalidate]; 
} 

감사합니다

+0

이것은 scheduledTimer를 사용하는 방법을 보여 주지만, 문제가 무엇인지, 그리고 이것이 어떻게 도움이되는지를 OP에 알리지 않습니다. – Jelle

관련 문제