gpt4 book ai didi

ios - 尝试做一个简单的倒计时应用程序但计数器没有倒计时?

转载 作者:行者123 更新时间:2023-11-29 02:19:30 26 4
gpt4 key购买 nike

我正在开发 Xcode 6 并尝试制作一个简单的倒计时应用程序。我的应用程序真的很简单。用户界面有一个标签和一个按钮。单击按钮时,应该从 10 开始倒计时。

这是我的代码:

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController

{
NSInteger count;
NSTimer *timer;
}

@property (weak, nonatomic) IBOutlet UILabel *timerLabel;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

-(IBAction)start {
count = 10;
timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
};

-(void)timerFired:(NSTimer *)timer {
count -=1;
self.timerLabel.text = [NSString stringWithFormat:@"%i",count];

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

}
- (void)viewDidLoad {
[super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}

@end

程序编译得很好,但是当我单击按钮开始倒计时时,没有任何反应。我哪里做错了?

编辑:非常感谢你们!问题解决了。我花了 3 个小时试图弄清楚我做错了什么,结果发现这是一个愚蠢的错误。啊。爱你堆栈溢出!

最佳答案

您已正确设置触发方法,但计时器并未实际触发。作为mentioned by Darren , 你想使用 scheduledTimerWithTimeInterval构造函数而不是 timerWithTimeInterval构造函数,除非您专门调用 [NSTimer fire],否则它不会触发。

因此,只需为此切换掉旧的构造函数:

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];

然后计时器应正确触发(每秒)并调用关联的方法:

enter image description here

关于ios - 尝试做一个简单的倒计时应用程序但计数器没有倒计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28335732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com