停止计时器应用程序 - Xcode

时间:2015-06-16 14:30:29

标签: ios objective-c timer

我正在尝试制作计时器应用。我可以使用Play按钮,但我无法使用Pause按钮。我已经看过一些关于Timer Apps的教程,其中大多数只使用了:[timer invalidate]代码,该方法只能停止当前标签(显示)中显示的时间。即使那段代码对我来说也不起作用,所以我尝试这样做,这样做更有意义,但仍然没有运气。

@implementation ViewController

int timerCounter=0;
NSTimer *timer;
NSString *label;
BOOL isPaused=NO;

-(IB Action) playButton:(id)sender{

     [timer invalidate];
     isPaused=NO;
     timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector: @selector(tick) userInfo:nil repeats:YES];
}

-(IBAction) pauseButton:(id)sender{

     [timer invalidate];
     isPaused=YES;

     label=[NSString stringWithFormat:@"%d",timerCounter];
    _labelTimer.text=label;
}

-(void) tick{

    if (isPaused==NO){
       timerCounter++;
    }

   label=[NSString stringWithFormat:@"%d",timerCounter];
  _labelTimer.text=label;
}

1 个答案:

答案 0 :(得分:1)

NSTimer API没有任何暂停方法。可用的是火灾或无效。关于你的代码,你正在使用全局变量 - 这不是一个好习惯,很可能是你调用的计时器的实例不一样,删除它们并在.m中的类扩展中添加一个属性:

@property (nonatomic, strong) NSTimer * timer;

然后用self.timer解决该属性。 如果这没有帮助,请检查按下时按钮是否调用该方法。

相关问题