简体   繁体   中英

Countdown timer that stops and reset on 0

Got an issue with my countdown timer who don't want to countdown from 60 and reset when 0 is reached. At the moment it just sets its label 0 and start counting down to -1, 2-... How do I get it to start from 60 on iOS in xcode?

.m file

#import "ViewController.h"

@interface ViewController ()
{
    int timeTick;
    NSTimer *timer;
}

@end

@implementation ViewController

- (IBAction)stopStartBtn:(id)sender {
    [timer invalidate];

    timeTick = 3;

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

-(void)myTicker{
    timeTick--;

    NSString *timeString =[[NSString alloc] initWithFormat:@"%d", timeTick];
    self.display.text = timeString;

    if(timer >= 0){
        [timer invalidate];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    timeTick = 3;
}

@end

.h File

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

    @property (strong, nonatomic) IBOutlet UILabel *display;
    - (IBAction)stopStartBtn:(id)sender;


    @end

Your code currently starts the timer at 0, decrements it, and then checks it it has reached 60. Obviously that won't happen.

If you want to start at 60 and stop at 0 then you need to set timeTick to 60 in viewDidLoad and check for a value of 0 in myTicker .

And don't forget to call [super viewDidLoad]; in your viewDidLoad method.

You also need to fix your check to see if you've reached zero. Right now you are looking at the timer pointer instead of timeTick integer.

Change:

if(timer >= 0){
    [timer invalidate];
}

to:

if (timeTick <= 0) {
    [timer invalidate];
}

You are also never setting your timer instance variable. You actually set a local variable of the same name.

Change:

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

to:

timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myTicker) userInfo:nil repeats:YES];
@interface Ovning1 ()
{
   int timeTick;
   NSTimer *timer;
}
@end

@implementation Ovning1


- (IBAction)stopStartBtn:(id)sender {

    [timer invalidate];

    timeTick = 60;

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

-(void)myTicker{

    timeTick--;

    NSString *timeString =[[NSString alloc] initWithFormat:@"%d", timeTick];
    self.display.text = timeString;


    if(timeTick <= 0){
        [timer invalidate];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM