做的一个倒计时的例子,代码如下:
现在的问题是 _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
1
lisonfan OP 在 alertAction 中添加了
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes]; 能实现倒计时了。 |
2
lisonfan OP 不知道为什么,会有两秒的延迟
|
3
lisonfan OP 延迟的问题解决了。。
tickAction 里 把 _sec-- 改成 --_sec |