剛剛有朋友讓我寫個倒計時器,我就簡單寫了一個,比較簡陋,大家可以在這個基礎上寫點更復雜的.好了,代碼里的注釋很詳細,上代碼.
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic, strong)NSTimer *timer;//定時器
@property(nonatomic, assign)CGFloat timeValue;//時間值
@property(nonatomic, strong)UILabel *label;//用于顯示時間
@property(nonatomic, strong)UIButton *button;//用于選擇暫停或是繼續倒計時
@end
static NSInteger flag = 0;
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
_label.font = [UIFont systemFontOfSize:50];
[self.view addSubview:_label];
_timeValue = 5.0;//初始化時間是5秒
_label.text = [NSString stringWithFormat:@"%.1f",_timeValue];//將_timeValue的值顯示再label上面
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timeChanged) userInfo:nil repeats:YES];//這個定時器沒隔0.1秒執行一次,并刷新_label的值
/*添加一個button用于控制暫停或是繼續倒計時*/
_button = [UIButton buttonWithType:UIButtonTypeSystem];
_button.frame = CGRectMake(200, 100, 200, 100);
[_button setTitle:@"暫停" forState:UIControlStateNormal];
[_button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button];
}
-(void)buttonAction
{
if (flag == 0) {
[_timer setFireDate:[NSDate distantFuture]];//暫停NSTimer
[_button setTitle:@"繼續" forState:UIControlStateNormal];
flag = 1;
}
else
{
[_timer setFireDate:[NSDate distantPast]];//繼續NSTimer
[_button setTitle:@"暫停" forState:UIControlStateNormal];
flag = 0;
}
}
-(void)timeChanged
{
_timeValue -= 0.1;//讓_timeValue值減1
_label.text = [NSString stringWithFormat:@"%.1f",_timeValue];
if (_timeValue <= 0.0) {
//當時間到了0,讓label的值為0.0,并且彈出一個UIAlertController讓用戶選擇確定還是重來
_label.text = @"0.0";
[_timer setFireDate:[NSDate distantFuture]];//暫停NSTimer
UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"時間到" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *stop = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *goon = [UIAlertAction actionWithTitle:@"重來" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//點擊重來時執行的操作,重置時間,并讓NSTimer恢復
_timeValue = 5.0;
[_timer setFireDate:[NSDate distantPast]];
}];
[alertControl addAction:stop];
[alertControl addAction:goon];
[self presentViewController:alertControl animated:YES completion:nil];//讓alertControl顯示出來
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
效果圖是這樣的
Simulator Screen Shot 2015年12月3日 下午10.09.14.png