iOS - 實(shí)現(xiàn)在有限label上 動(dòng)態(tài)顯示所有文字

效果如下:

001.gif

點(diǎn)擊下載查看demo

思路

  1. 創(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];
  1. 給內(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;
  1. 給label添加動(dòng)畫(huà)
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ō)再見(jiàn),不說(shuō)再見(jiàn),越長(zhǎng)大越孤單";
testLabel.textColor = [UIColor yellowColor];
testLabel.font = [UIFont systemFontOfSize:23];
testLabel.backgroundColor = [UIColor grayColor];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容