计时器不会停止,不会停在stopButtonPressed
中,如果sec
值为0则不会停止。
计时器应该例如计数从100到0.如果值== 0或按下停止按钮,计时器应该停止!但它仍在继续计算。
我的错误在哪里? 我尝试了不同的方法但没有任何作用。
以下是代码:
<。>文件中的
@property (weak, nonatomic) NSTimer *countdownTimer;
<。>文件中的
- (void)timer {
sec = sec - 1;
int minutes = sec / 60;
int seconds = sec - (minutes * 60);
[_timerLabel setText:[NSString stringWithFormat:@"%02d:%02d",minutes,seconds]];
if (sec == 0) {
[_countdownTimer invalidate];
_countdownTimer = nil;
}
}
- (void)startTimer {
_countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timer) userInfo:nil repeats:YES];
}
- (IBAction)startButtonPressed:(id)sender {
[self startTimer];
[_startButton setHidden:YES];
[_stopButton setHidden:NO];
}
- (IBAction)stopButtonPressed:(id)sender {
[_stopButton setHidden:YES];
[_countdownTimer invalidate];
[_startButton setHidden:NO];
}
谢谢!
答案 0 :(得分:-2)
我已经尝试过这段代码而且效果很好,当你按下stopButton并且sec == 0时,计时器停止;
#import "ViewController.h"
@interface ViewController (){
NSTimer*_countdownTimer;
int sec;
}
@property (nonatomic,weak) IBOutlet UILabel*_timerLabel;
@property (nonatomic,weak) IBOutlet UIButton*_startButton;
@property (nonatomic,weak) IBOutlet UIButton*_stopButton;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
sec=100;
}
- (void)timer {
sec = sec - 1;
int minutes = sec / 60;
int seconds = sec - (minutes * 60);
[self._timerLabel setText:[NSString stringWithFormat:@"%02d:%02d",minutes,seconds]];
if (sec == 0) {
[_countdownTimer invalidate];
_countdownTimer = nil;
}
}
- (void)startTimer {
_countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timer) userInfo:nil repeats:YES];
}
- (IBAction)startButtonPressed:(id)sender {
[self startTimer];
[self._startButton setHidden:YES];
[self._stopButton setHidden:NO];
}
- (IBAction)stopButtonPressed:(id)sender {
[self._stopButton setHidden:YES];
[_countdownTimer invalidate];
_countdownTimer=nil;
[self._startButton setHidden:NO];
}