照例先看下效果圖:
思路
建立一個view
作為所有內容的父控制項, 並且添加到上面一個 label
, 作為顯示文字的載體
UILabel* contentLabel = [[UILabel alloc] init];[contentLabel sizeToFit];contentLabel.backgroundColor = [UIColor clearColor]; _contentLabel = contentLabel; [self addSubview:self.contentLabel];
給內容view
的layer
添加一個mask
層, 並且設定其範圍為整個view
的bounds
, 這樣就讓超出view
的內容不會顯示出來
CAShapeLayer* maskLayer = [CAShapeLayer layer];maskLayer.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;self.layer.mask = maskLayer;
給label
添加動畫
CAKeyframeAnimation* keyFrame = [CAKeyframeAnimation animation];keyFrame.keyPath = @"transform.translation.x";keyFrame.values = @[@(0), @(-space), @(0)];keyFrame.repeatCount = NSIntegerMax;keyFrame.duration = self.speed * self.contentLabel.text.length;keyFrame.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut], [CAMediaTimingFunction functionWithControlPoints:0 :0 :0.5 :0.5]];keyFrame.delegate = self;[self.contentLabel.layer addAnimation:keyFrame forKey:nil];
使用方法
// 建立CFDynamicLabel* testLabel = [[CFDynamicLabel alloc] initWithFrame:CGRectMake(100, 300, 180, 21)];// 設定捲動速度testLabel.speed = 0.6;[self.view addSubview:testLabel];// 設定基本屬性testLabel.text = @"我不想說再見,不說再見,越長大越孤單";testLabel.textColor = [UIColor yellowColor];testLabel.font = [UIFont systemFontOfSize:23];testLabel.backgroundColor = [UIColor grayColor];
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流。