美文网首页
NSTimer定时器、视图对象的移动

NSTimer定时器、视图对象的移动

作者: 李琪_59dc | 来源:发表于2017-10-11 09:54 被阅读0次

    定时器写在视图控制器ViewController类中:

    • ViewController.h
    //定义一个定时器对象
    //可以在固定时间发送一个消息
    //通过此消息来调用相应的时间函数方法
    @property(strong,nonatomic)NSTimer *timerView;
    
    • 以按钮点击控制定时器开始和结束为例
    • ViewController.m
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        //创建一个普通按钮
        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, 200, 80, 40);
        [btnStop setTitle:@"停止定时器" forState:UIControlStateNormal];
        
        [btnStop addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:btnStop];
    }
    
    • 然后编写启动和停止事件:
    //ViewController.m
    //启动按钮响应事件
    -(void)pressStart{
        //NSTimer的类方法创建一个定时器并且启动这个定时器
        //P1:每隔多久调用定时器函数
        //P2:调用定时器函数的对象
        //P3:定时器函数对象
        //P4:可以传入定时器函数中一个参数,没有参数时写nil
        //P5;定时器是否重复操作 YES重复 NO只调用一次
        //返回值是一个新建的定时器对象
        _timerView = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer:) userInfo:@"lychee" repeats:YES];
    }
    //定时器函数
    //可以将定时器本身作为参数传入
    -(void)updateTimer:(NSTimer *)timer{
        NSLog(@"TEST!!!name=%@",timer.userInfo);
    }
    //停止按钮响应事件
    -(void)pressStop{
        if(_timerView!=nil){
            [_timerView invalidate];
        }
    }
    
    

    根据定时器移动视图对象

    • 在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;
    
    • 然后在定时器函数中移动视图对象
    //获取界面中的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);
    

    相关文章

      网友评论

          本文标题:NSTimer定时器、视图对象的移动

          本文链接:https://www.haomeiwen.com/subject/ekuiyxtx.html