美文网首页
CADisplaylink跑马灯

CADisplaylink跑马灯

作者: 倪大头 | 来源:发表于2018-05-08 18:28 被阅读12次

    CADisplayLink 是一个用于显示的定时器,以屏幕刷新频率同步绘图

    用UILabel举例:

    runLabel = [[UILabel alloc]init];
    runLabel.text = @"hello world";
    runLabel.textColor = [UIColor whiteColor];
    runLabel.font = [UIFont systemFontOfSize:18];
    [runLabel sizeToFit];
    runLabel.center = CGPointMake(UI_SCREEN_WIDTH + runLabel.frame.size.width/2, kScaleY*200 + runLabel.frame.size.height/2);
    [self.view addSubview:runLabel];
    

    创建定时器:

    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(viewRun)];
    //[displayLink setPaused:YES];//暂停
    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];//把它加入到runloop里它才会开始运作
    

    CADisplayLink有一个整型的frameInterval属性,指定了间隔多少帧之后才执行,默认值是1,意味着每次屏幕更新之前都会执行一次,上面代码反复执行一个 viewRun 方法:

    - (void)viewRun {
        if (runLabel.center.x < -runLabel.frame.size.width/2) {
            runLabel.center = CGPointMake(UI_SCREEN_WIDTH + runLabel.frame.size.width/2, runLabel.center.y);
        }else {
            runLabel.center = CGPointMake(runLabel.center.x - 1, runLabel.center.y);
        }
    }
    

    viewRun方法只是移动了视图的center,随着屏幕刷新label一直保持移动,移动到屏幕尽头执行返回最初位置的代码

    相关文章

      网友评论

          本文标题:CADisplaylink跑马灯

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