[英]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.