5

我有一个使用计时器的游戏。我想这样做,以便用户可以选择一个按钮并暂停该计时器,当他们再次单击该按钮时,它将取消暂停该计时器。我已经有了定时器的代码,只需要一些帮助来暂停定时器和双动作按钮。

定时器代码:

-(void)timerDelay {

    mainInt = 36;

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(countDownDuration)
                                       userInfo:nil
                                        repeats:YES];
}

-(void)countDownDuration {

    MainInt -= 1;

    seconds.text = [NSString stringWithFormat:@"%i", MainInt];
    if (MainInt <= 0) {
        [timer invalidate];
        [self delay];
    }

}
4

2 回答 2

18

这很容易。

// Declare the following variables
BOOL ispaused;
NSTimer *timer;
int MainInt;

-(void)countUp {
    if (ispaused == NO) {
        MainInt +=1;
        secondField.stringValue = [NSString stringWithFormat:@"%i",MainInt];
    }
}

- (IBAction)start1Clicked:(id)sender {
    MainInt=0;
    timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countUp) userInfo:Nil repeats:YES];
}

- (IBAction)pause1Clicked:(id)sender {
    ispaused = YES;
}

- (IBAction)resume1Clicked:(id)sender {
    ispaused = NO;
}
于 2013-08-13T04:01:19.333 回答
4

NSTimer 中没有暂停和恢复功能。您可以像下面的代码一样暗示它。

- (void)startTimer
{
    m_pTimerObject = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self  selector:@selector(fireTimer:) userInfo:nil repeats:YES];
}

- (void)fireTimer:(NSTimer *)inTimer
{
    // Timer is fired.
}

- (void)resumeTimer
{
    if(m_pTimerObject)
    {
        [m_pTimerObject invalidate];
        m_pTimerObject = nil;        
    }
    m_pTimerObject = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self  selector:@selector(fireTimer:) userInfo:nil repeats:YES];
}

- (void)pauseTimer
{
    [m_pTimerObject invalidate];
    m_pTimerObject = nil;
}
于 2013-08-13T02:44:07.280 回答