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

来源:互联网 发布:学而知不足,思而得远虑 编辑:程序博客网 时间:2024/06/06 07:10

创建启动和停止 定时器的按钮 ,和添加视图:

#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];    }}


1 0
原创粉丝点击