您的位置:首页 > 其它

通过按钮 启动NSTimer定时器 控制视图view移动效果

2017-01-15 13:20 441 查看
创建启动和停止 定时器的按钮 ,和添加视图:

#pragma  mark - NSTimer定时器

- (void)setTimeCreat{

//创建 启动定时器按钮
UIButton* btn =[UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame =CGRectMake(100, 100, 80, 40);
[btn setTitle:@"启动定时器" forState:UIControlStateNormal];
//给按钮添加 事件
[btn addTarget:self action:@selector(StartTime) forControlEvents:UIControlEventTouchUpInside];
//添加按钮
[self.view addSubview:btn];

//创建 启动定时器按钮
UIButton* btnStop =[UIButton buttonWithType:UIButtonTypeRoundedRect];
btnStop.frame =CGRectMake(100, 200, 80, 40);
[btnStop setTitle:@"停止定时器" forState:UIControlStateNormal];
//给按钮添加 事件
[btnStop addTarget:self action:@selector(StopTime) forControlEvents:UIControlEventTouchUpInside];
//添加按钮
[self.view addSubview:btnStop];

//添加视图
UIView* view =[[UIView alloc] init];
view.frame =CGRectMake(0, 0, 80, 80);
view.backgroundColor =[UIColor orangeColor];

[self.view addSubview:view];
//设置标签值 ,通过父视图 对象以及 子视图的标签值 可以获得子视图对象
view.tag =101;

}


定义 定时器触发事件 ,移动视图的效果: 

//定时器事件
- (void)updateTimer:(NSTimer *)timer{
//定时器本身作为参数
NSLog(@"name= %@" ,timer.userInfo);

//tag从100开始
UIView* view =[self.view viewWithTag:101];
view.frame =CGRectMake(view.frame.origin.x +1, view.frame.origin.y +1, 80, 80);
}


定义两个 按钮触发事件:

//启动定时器 按钮触发 ,多按几次可以达到 加速的效果
- (void)StartTime{

//给定时器添加 触发事件 ,时间戳TimeInterval 以秒为单位
_timer =[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer:) userInfo:@"小鑫" repeats:YES];
}

- (void)StopTime{

if(_timer != nil){
//停止定时器
[_timer invalidate];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐