效果如下:
001.gif
思路
- 創(chuàng)建一個(gè)view 作為所有內(nèi)容的父控件, 并且添加到上面一個(gè) label, 作為顯示文字的載體
UILabel* contentLabel = [[UILabel alloc] init];
[contentLabel sizeToFit];
contentLabel.backgroundColor = [UIColor clearColor]; _contentLabel = contentLabel; [self addSubview:self.contentLabel];
- 給內(nèi)容view的layer添加一個(gè)mask層, 并且設(shè)置其范圍為整個(gè)view的bounds, 這樣就讓超出view的內(nèi)容不會(huì)顯示出來(lái)
CAShapeLayer* maskLayer = [CAShapeLayer layer];
maskLayer.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
self.layer.mask = maskLayer;
- 給label添加動(dòng)畫
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];
使用方法
// 創(chuàng)建
CFDynamicLabel* testLabel = [[CFDynamicLabel alloc] initWithFrame:CGRectMake(100, 300, 180, 21)];
// 設(shè)置滾動(dòng)速度
testLabel.speed = 0.6;
[self.view addSubview:testLabel];
// 設(shè)置基本屬性
testLabel.text = @"我不想說(shuō)再見,不說(shuō)再見,越長(zhǎng)大越孤單";
testLabel.textColor = [UIColor yellowColor];
testLabel.font = [UIFont systemFontOfSize:23];
testLabel.backgroundColor = [UIColor grayColor];