可以在每隔固定时间发送一个消息
通过此消息来调用相应的时间函数
通过此函数可在固定时间段来完成一个根据时间间隔的人物
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];
UIButton* btnStop=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btnStop.frame=CGRectMake(100, 150, 80, 40);
[btnStop setTitle:@"停止定时器" forState:UIControlStateNormal];
[btnStop addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnStop];
UIView* view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
view.backgroundColor=[UIColor orangeColor];
view.tag=103;
[self.view addSubview:view];
创建并开始定时器函数
-(void) pressStart
{
//NSTimer的类方法创建一个定时器并启动这个定时器
//p1:每个多长时间调用定时器函数,以秒为单位
//p2:表示实现定时器的函数的对象
//p3:定时器函数对象
//p4:可以传入定时器里的一个参数,
//p5:定时器是否重复 YES为重复
//返回一个新建好的定时器对象
_timerView=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(uploadTimer:) userInfo:@"小明" repeats:YES];
}
停止函数
-(void) pressStop
{
if (_timerView!=nil) {
//停止计时器
[_timerView invalidate];
}
}
定时器函数 移动view
//定时器函数
-(void) uploadTimer:(NSTimer*) timer
{
NSLog(@"test......name=%@",timer.userInfo);
UIView* view=[self.view viewWithTag:103];
view.frame=CGRectMake(view.frame.origin.x+5, view.frame.origin.y+5, 80, 80);
}