2013-05-22 2 views
0

현재 스톱워치가 필요하다고 말하는 게임을 개발 중입니다. 사용자가 게임 화면에 들어가는 재생 버튼을 탭하면 1 분 동안 중지 시계 수가 내려갑니다. 01 : 00,00 : 59,00 : 58 등. 그 이유로 나는 NSTimer가 스톱워치를 구현하는 이상적인 선택 일 것이라고 판단했다. 나는 라벨을 가져 와서 NSTimer의 인스턴스를 만들고, 시간 간격을 지정하고 감소시키기 시작했다. 타이머 라벨의 값, 즉 :다른보기로 이동 한 후 NSTimer를 재설정합니다.

-(void)viewDidAppear:(BOOL)animated 
{ 
    self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(viewWillAppear:) userInfo:nil repeats:YES]; 
    [super viewDidAppear:YES]; 
} 

-(void)viewWillAppear:(BOOL)animated 
{ 
    static int currentTime = 60; 
    int newTime = currentTime--; 
    int minutesRemaining = newTime/60; // integer division, truncates fractional part 
    int secondsRemaining = newTime % 60; // modulo division 

    self.timerLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutesRemaining, secondsRemaining]; 

    if ([self.timerLabel.text isEqualToString:@"00:00"]) 
    { 
     [stopWatchTimer invalidate]; 
    } 
    [super viewWillAppear:YES]; 
} 

여기서 문제 01 실행하는 타이머가 시작됩니다 : 00,00 : 59,00 : 58, 초 53로 말을 내가 다른보기를 탐색하고 와서 계속을 다시, 그것은 00 : 53,00 : 52에서 계속되고 있습니다. 그러나 나는 01:00과 th 내가 viewDidDisappear에 NSTimer을 무효화하여 구현에 즉

-(void)viewDidDisappear:(BOOL)animated 
{ 
    if ([stopWatchTimer isValid]) 
    { 
     [stopWatchTimer invalidate]; 
     self.stopWatchTimer = nil; 
    } 
    [super viewDidDisappear:YES]; 
} 

여전히 같은 문제가 존재!

문제에 대한 많은 연구를 수행했으며 유용하고 효과적인 답변을 찾지 못했습니다.

몇 사람은 나를 안내해 주실 수 있습니까, 어떤 도움을 주시면 감사하겠습니다.

미리 감사합니다 :)

답변

1

의 모든 일 당신은 타이머의 선택 viewWillAppear를 사용합니다. viewWillAppear은 뷰가 화면에 나타날 때 호출되는 viewController의 메서드이므로 직접 호출하면 안됩니다. 대신 타이머를 감소 자신의 방법을 만들 : 타이머가 매 초마다 호출에 대한 책임이 기술을

-(void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 
    self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES]; 
    currentTime = 60; // This could be an instance variable 
    self.timerLabel.text = @"01:00"; 
} 


-(void)updateTime { 
    int newTime = currentTime--; 
    int minutesRemaining = newTime/60; // integer division, truncates fractional part 
    int secondsRemaining = newTime % 60; // modulo division 

    self.timerLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutesRemaining, secondsRemaining]; 

    if ([self.timerLabel.text isEqualToString:@"00:00"]) 
    { 
     [self.stopWatchTimer invalidate]; 
    } 
} 

-(void)viewDidDisappear:(BOOL)animated 
{ 
[super viewDidDisappear:animated]; 
    if ([self.stopWatchTimer isValid]) 
    { 
    [self.stopWatchTimer invalidate]; 
    self.stopWatchTimer = nil; 
    } 
} 

,하지만 당신은 아마 몇 초 후 타이밍 문제가됩니다. 보다 정확한 타이밍을 얻으려면 카운트 다운을 시작한 시간을 저장하고 updateTime 호마다 현재 시간과 저장된 시작 시간을 비교해야합니다.

사용자 인터페이스에 추가

@property (nonatomic) NSTimeInterval startTime; 

을 다음 구현 :

-(void)viewDidAppear:(BOOL)animated 
{ 
    self.startTime = [NSDate timeIntervalSinceReferenceDate]; 
    self.duration = 60; // How long the countdown should be 
    self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 
                  target:self 
                 selector:@selector(updateTime) 
                 userInfo:nil 
                  repeats:YES]; 
    self.timerLabel.text = @"01:00"; // Make sure this represents the countdown time 
} 

-(void)updateTime { 

    int newTime = self.duration - (round([NSDate timeIntervalSinceReferenceDate] - self.startTime)); 
    int minutesRemaining = newTime/60; // integer division, truncates fractional part 
    int secondsRemaining = newTime % 60; // modulo division 

    self.timerLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutesRemaining, secondsRemaining]; 

    if (newTime < 1) 
    { 
    [self.stopWatchTimer invalidate]; 

    /* Do more stuff here */ 

    } 
} 

-(void)viewDidDisappear:(BOOL)animated 
{ 
[super viewDidDisappear:animated]; 
    if ([self.stopWatchTimer isValid]) 
    { 
    [self.stopWatchTimer invalidate]; 
    self.stopWatchTimer = nil; 
    } 
} 

일부 추가 (무관) 주석을 코드에 :

viewDidDisappear: 구현에 animated 매개 변수를 전달 super 호출 : [super viewDidDisappear : animated]; viewDidAppear:을 구현할 때 animated 매개 변수를 super에 전달하면 아무 것도하지 말고 먼저 메서드에서 super를 호출해야합니다.

+0

완벽 함 Marcel, 효과가 있지만 유일한 문제는 이전에 표시되는 레이블입니다. 시간이 00:51이라고 말한 다음 01:00로 변경하고 타이머는 정상적으로 작동하지만보기로 돌아 가면 이전 시간이 표시되는 것을 원하지 않습니다. 감사합니다. :) –

+0

예제 코드를 업데이트했습니다. 보기가 나타나 자마자 레이블에 텍스트를 설정해야합니다. – Marcel

+0

Marcel이 효과가 있었지만 약간의 수정을 가해서 문제없이 작동하게 만들었습니다. 귀하의 답변을 편집 할 계획입니까? –

관련 문제