標籤:
效果如下:
點擊下載查看demo思路(1)建立一個view 作為所有內容的父控制項, 並且添加到上面一個 label, 作為顯示文字的載體
UILabel* contentLabel = [[UILabel alloc] init];[contentLabel sizeToFit];
contentLabel.backgroundColor = [UIColor clearColor]; _contentLabel = contentLabel; [self addSubview:self.contentLabel];
(2)給內容view的layer添加一個mask層, 並且設定其範圍為整個view的bounds, 這樣就讓超出view的內容不會顯示出來
CAShapeLayer* maskLayer = [CAShapeLayer layer];maskLayer.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;self.layer.mask = maskLayer;
(3)給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];
iOS - 實現在有限label上 動態顯示所有文字