定時器寫在視圖控制器ViewController類中:
- ViewController.h
//定義一個定時器對象
//可以在固定時間發(fā)送一個消息
//通過此消息來調(diào)用相應的時間函數(shù)方法
@property(strong,nonatomic)NSTimer *timerView;
- 以按鈕點擊控制定時器開始和結(jié)束為例
- ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//創(chuàng)建一個普通按鈕
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100, 100, 80, 40);
[btn setTitle:@"啟動定時器" forState:UIControlStateNormal];
//給啟動按鈕設置響應操作方法
[btn addTarget:self action:@selector(pressStart) forControlEvents:UIControlEventTouchUpInside];
//將按鈕添加到當前視圖中
[self.view addSubview:btn];
//同理設置結(jié)束按鈕
UIButton *btnStop = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnStop.frame = CGRectMake(100, 200, 80, 40);
[btnStop setTitle:@"停止定時器" forState:UIControlStateNormal];
[btnStop addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnStop];
}
- 然后編寫啟動和停止事件:
//ViewController.m
//啟動按鈕響應事件
-(void)pressStart{
//NSTimer的類方法創(chuàng)建一個定時器并且啟動這個定時器
//P1:每隔多久調(diào)用定時器函數(shù)
//P2:調(diào)用定時器函數(shù)的對象
//P3:定時器函數(shù)對象
//P4:可以傳入定時器函數(shù)中一個參數(shù),沒有參數(shù)時寫nil
//P5;定時器是否重復操作 YES重復 NO只調(diào)用一次
//返回值是一個新建的定時器對象
_timerView = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer:) userInfo:@"lychee" repeats:YES];
}
//定時器函數(shù)
//可以將定時器本身作為參數(shù)傳入
-(void)updateTimer:(NSTimer *)timer{
NSLog(@"TEST!!!name=%@",timer.userInfo);
}
//停止按鈕響應事件
-(void)pressStop{
if(_timerView!=nil){
[_timerView invalidate];
}
}
根據(jù)定時器移動視圖對象
- 在ViewController.m中,viewDidLoad中添加UIView控件
UIView *view = [[UIView alloc]init];
view.frame = CGRectMake(0, 0, 80, 80);
view.backgroundColor = [UIColor orangeColor];
[self.view addSubview:view];
view.tag = 101;
- 然后在定時器函數(shù)中移動視圖對象
//獲取界面中的UIView控件
UIView *view = [self.view viewWithTag:101];
view.frame = CGRectMake(view.frame.origin.x+1, view.frame.origin.y+1, view.frame.size.height, view.frame.size.width);