做的一个倒计时的例子,代码如下:
现在的问题是 _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(tickAction) userInfo:nil repeats:YES]; 这段代码不起作用。。
@interface ViewController (){
UIDatePicker * _myPicker;
NSTimeInterval _sec;
UILabel * _label;
UIButton * _btn;
NSTimer * _timer;
}
@end
@implementation ViewController
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self creatPicker];
[self creatButton];
[self creatLabel];
}
(void)creatPicker{
_myPicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(20, 20, 0, 0)];
_myPicker.datePickerMode = UIDatePickerModeCountDownTimer;
[self.view addSubview:_myPicker];
}
(void)creatButton{
_btn = [[UIButton alloc] initWithFrame:CGRectMake(50, 270, 100, 50)];
[_btn setTitle:@"开始" forState:UIControlStateNormal];
[_btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_btn];
}
(void)btnAction:(UIButton*)btn{
_sec = _myPicker.countDownDuration;
[self creatAlert];
}
(void)creatAlert{
NSString * str = [NSString stringWithFormat:@"开始倒计时,您还剩[%.f]秒",_sec];
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"倒计时" message:str preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[self alertAction];
}];
UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:okAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
}
(void)alertAction{
_label.text = [NSString stringWithFormat:@"%.f",_sec];
_btn.enabled = NO;
_myPicker.enabled = NO;
_timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(tickAction) userInfo:nil repeats:YES];
}
(void)tickAction{
float letSec = _sec--;
_label.text = [NSString stringWithFormat:@"%.f",letSec];
NSLog(@"%.f",_sec);
if (letSec <= 0) {
[_timer invalidate];
_btn.enabled = YES;
_myPicker.enabled = YES;
}
}
(void)creatLabel{
_label = [[UILabel alloc] initWithFrame:CGRectMake(200, 270, 100, 50)];
_label.text = @"0";
_label.textColor = [UIColor redColor];
[self.view addSubview:_label];
}
(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.