繁体   English   中英

倒数计时器将停止并重置为0

[英]Countdown timer that stops and reset on 0

我的倒数计时器遇到了一个问题,谁不想从60开始倒数​​,并在达到0时重置。 目前,它只是将其标签设置为0,然后开始递减为-1、2-。...如何在xcode上的iOS上从60开始?

.m文件

#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文件

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

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


    @end

您的代码当前将计时器从0开始,将其递减,然后检查其是否已达到60。显然,这不会发生。

如果timeTick 60开始并在0处停止,则需要在viewDidLoad中将timeTick设置为60并在myTicker检查值0

并且不要忘记调用[super viewDidLoad]; 在您的viewDidLoad方法中。

您还需要修正检查以查看是否达到零。 现在,您正在查看timer指针,而不是timeTick整数。

更改:

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

至:

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

您也永远不会设置timer实例变量。 您实际上设置了一个具有相同名称的局部变量。

更改:

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

至:

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];
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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