最近做项目的时候遇到一个需求,由于App兼容的语言类型太多,导致App内很多标签显示的文字不全,这时候需要滚动去显示。需求类似下面这个样子。
思考
1.整个App的label去做一个滚动显示,首先要考虑到性能问题,性能问题的话就不考虑使用UIView层去实现该效果,因此,文字滚动层考虑用Layer去处理。 2.能够影响到文本显示和是否能完全显示文本的属性有text、frame、font、textColor,因此我们需要对这几项属性进行处理。
在设置text的属性的时候,我们需要判断text的长度是否大于label的长度, 如果大于label的长度,我们需要将text文本处理到layer层,并且做滚动动画。在这是frame和font的时候我们需要重新做该判断,因为这两个属性影响了label的长度和文本的大小,设置textColor的时候我们需要把layer上的文本颜色也相应修改成该颜色。
实现
创建一个UILabel的子类,并且添加CATextLayer的属性
import UIKit
class LCAutoScrollLabel: UILabel {
private var textLayer : CATextLayer = CATextLayer()
private var shouldScroll : Bool = false
}
重写以上四个属性的set方法,加上判断是否需要滚动的逻辑
override var text: String? {
didSet {
shouldScroll = false
///把String转化成NSString,根据文本和Font得到文本的Size
let textString : NSString = NSString(string: self.text ?? "")
let size = textString.size(withAttributes: [NSAttributedString.Key.font : self.font!])
let stringWidth = size.width
let labelWidth = frame.size.width
if labelWidth < stringWidth {
shouldScroll = true
}
if shouldScroll
{
/// 如果判断需要滚动,设置textLayer的属性
let textString : NSString = self.text as NSString? ?? ""
let size = textString.size(withAttributes: [NSAttributedString.Key.font : self.font!])
let stringWidth = size.width
let stringHeight = size.height
textLayer.frame = CGRect(x: 0, y: (frame.height - stringHeight)/2, width: stringWidth, height: stringHeight)
textLayer.string = text
textLayer.alignmentMode = .center
textLayer.font = font
textLayer.fontSize = font.pointSize
textLayer.foregroundColor = self.textColor.cgColor
/// 动画
let ani = CABasicAnimation(keyPath: "position.x")
ani.toValue = -textLayer.frame.width
ani.fromValue = textLayer.frame.width
ani.duration = 4
ani.fillMode = .backwards
ani.repeatCount = 1000000000.0
ani.isRemovedOnCompletion = false
textLayer.add(ani, forKey: nil)
layer.addSublayer(textLayer)
}
else
{
/// 如果不需要滚动,移除动画和layer
textLayer.removeAllAnimations()
textLayer.removeFromSuperlayer()
}
}
}
因为四个重写的set方法里面逻辑基本一致,整理一下代码
override var text: String? {
didSet {
shouldScroll = shouldAutoScroll()
setTextLayerScroll()
}
}
override var font: UIFont! {
didSet {
shouldScroll = shouldAutoScroll()
setTextLayerScroll()
}
}
override var frame: CGRect {
didSet {
shouldScroll = shouldAutoScroll()
setTextLayerScroll()
}
}
override var textColor: UIColor! {
didSet {
textLayer.foregroundColor = textColor.cgColor
}
}
func setTextLayerScroll() {
if shouldScroll
{
setTextLayer()
textLayer.add(getLayerAnimation(), forKey: nil)
layer.addSublayer(textLayer)
}
else
{
textLayer.removeAllAnimations()
textLayer.removeFromSuperlayer()
}
}
func shouldAutoScroll() -> Bool {
var shouldScroll = false
let textString : NSString = NSString(string: self.text ?? "")
let size = textString.size(withAttributes: [NSAttributedString.Key.font : self.font!])
let stringWidth = size.width
let labelWidth = frame.size.width
if labelWidth < stringWidth {
shouldScroll = true
}
return shouldScroll
}
func setTextLayer() {
let textString : NSString = self.text as NSString? ?? ""
let size = textString.size(withAttributes: [NSAttributedString.Key.font : self.font!])
let stringWidth = size.width
let stringHeight = size.height
textLayer.frame = CGRect(x: 0, y: (frame.height - stringHeight)/2, width: stringWidth, height: stringHeight)
textLayer.string = text
textLayer.alignmentMode = .center
textLayer.font = font
textLayer.fontSize = font.pointSize
textLayer.foregroundColor = self.textColor.cgColor
}
func getLayerAnimation() -> CABasicAnimation {
let ani = CABasicAnimation(keyPath: "position.x")
ani.toValue = -textLayer.frame.width
ani.fromValue = textLayer.frame.width
ani.duration = 4
ani.fillMode = .backwards
ani.repeatCount = 1000000000.0
ani.isRemovedOnCompletion = false
return ani
}
测试结果得到如下结果,因为忘记处理label自己本身显示的文本。
我们可以出重写drawText的方法,根据是否需要滚动的判断去决定是否要显示text
override func drawText(in rect: CGRect) {
if !shouldScroll
{
super.drawText(in: rect)
}
}
经过简单测试,无论是改变font、frame、text都能够正常判断并且达到想要的效果。
但是有一个新的问题来了,由于项目是老项目,代码量已经十分庞大,如果要一个一个去把以前使用UILabel的地方全部替换成这个类,是一项非常耗时的工作,由于工期紧张,显然是给不了我这么多时间的。这时候我们就要用到我们的黑魔法Runtime了
黑魔法Runtime修改系统方法,快速达到目的
我们创建一个UILabel的分类,并且根据我们现有代码的逻辑,得到如下代码
#import "UILabel+AutoScroll.h"
#import <objc/runtime.h>
static NSString * textLayer = @"textLayer";
static NSString * scrollAnimation = @"scrollAnimation";
@implementation UILabel (AutoScroll)
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
/// 替换系统方法,我们需要重写的方法我们都要替换
Method setTextMethod = class_getInstanceMethod(self, @selector(setText:));
Method setColorMethod = class_getInstanceMethod(self, @selector(setTextColor:));
Method setFontMethod = class_getInstanceMethod(self, @selector(setFont:));
Method setFrameMethod = class_getInstanceMethod(self, @selector(setFrame:));
Method drawTextMethon = class_getInstanceMethod(self, @selector(drawTextInRect:));
Method scrollSetTextMethod = class_getInstanceMethod(self, @selector(autoScrollSetText:));
Method scrollSetColorMethod = class_getInstanceMethod(self, @selector(autoScrollSetTextColor:));
Method scrollSetFontMethod = class_getInstanceMethod(self, @selector(autoScrollSetFont:));
Method scrollSetFrameMethod = class_getInstanceMethod(self, @selector(autoScrollSetFrame:));
Method scrollDrawText = class_getInstanceMethod(self, @selector(autoScrollDrawText:));
method_exchangeImplementations(setTextMethod, scrollSetTextMethod);
method_exchangeImplementations(setColorMethod, scrollSetColorMethod);
method_exchangeImplementations(setFontMethod, scrollSetFontMethod);
method_exchangeImplementations(setFrameMethod, scrollSetFrameMethod);
method_exchangeImplementations(drawTextMethon, scrollDrawText);
});
}
/// 用于替换系统setText方法
/// @param text 标签显示的文字
- (void)autoScrollSetText:(NSString *)text
{
[self autoScrollSetText:text];
// 这句是为了让textlayer超出label的部分不显示
self.layer.masksToBounds = true;
[self setTextLayerScroll];
}
/// 用于替换系统setTextColor方法
/// @param color 文字颜色
- (void)autoScrollSetTextColor:(UIColor *)color
{
[self autoScrollSetTextColor:color];
[self setTextLayerScroll];
}
/// 用于替换系统的setFont方法
/// @param font 字体
- (void)autoScrollSetFont:(UIFont *)font
{
[self autoScrollSetFont:font];
[self setTextLayerScroll];
}
/// 用于替换系统的setFrame方法
/// @param frame 坐标
- (void)autoScrollSetFrame:(CGRect)frame
{
[self autoScrollSetFrame:frame];
[self setTextLayerScroll];
}
/// 用于替换系统的drawText方法
/// @param rect frame
- (void)autoScrollDrawText:(CGRect)rect
{
BOOL shouldScroll = [self shouldAutoScroll];
if (!shouldScroll)
{
[self autoScrollDrawText:rect];
}
}
/// 根据文字长短自动判断是否需要显示TextLayer,并且滚动
- (void)setTextLayerScroll
{
BOOL shouldScroll = [self shouldAutoScroll];
CATextLayer * textLayer = [self getTextLayer];
if (shouldScroll)
{
CABasicAnimation * ani = [self getAnimation];
[textLayer addAnimation:ani forKey:nil];
[self.layer addSublayer:textLayer];
}
else
{
[textLayer removeAllAnimations];
[textLayer removeFromSuperlayer];
}
}
/// runtime存放textLayer,避免多次生成
- (CATextLayer *)getTextLayer
{
CATextLayer * layer = objc_getAssociatedObject(self, &textLayer);
if (!layer) {
layer = [CATextLayer layer];
objc_setAssociatedObject(self, &textLayer, layer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
CGSize size = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
CGFloat stringWidth = size.width;
CGFloat stringHeight = size.height;
layer.frame = CGRectMake(0, (self.frame.size.height - stringHeight)/2, stringWidth, stringHeight);
layer.alignmentMode = kCAAlignmentCenter;
layer.font = (__bridge CFTypeRef _Nullable)(self.font.fontName);
layer.fontSize = self.font.pointSize;
layer.foregroundColor = self.textColor.CGColor;
layer.string = self.text;
return layer;
}
/// runtime存放动画对象,避免多次生成
- (CABasicAnimation *)getAnimation
{
CABasicAnimation * ani = objc_getAssociatedObject(self, &scrollAnimation);
if (!ani) {
ani = [CABasicAnimation animationWithKeyPath:@"position.x"];
objc_setAssociatedObject(self, &scrollAnimation, ani, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
CATextLayer * textLayer = [self getTextLayer];
id toValue = @(-textLayer.frame.size.width);
id fromValue = @(textLayer.frame.size.width);
ani.toValue = toValue;
ani.fromValue = fromValue;
ani.duration = 4;
ani.fillMode = @"backwards";
ani.repeatCount = 1000000000.0;
ani.removedOnCompletion = false;
return ani;
}
/// 判断是否需要滚动
- (BOOL)shouldAutoScroll
{
BOOL shouldScroll = false;
CGSize size = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
CGFloat stringWidth = size.width;
CGFloat labelWidth = self.frame.size.width;
if (labelWidth < stringWidth) {
shouldScroll = true;
}
return shouldScroll;
}
@end
最后在pch文件中导入该分类,项目中所有的UILabel就能自动判断并且实现滚动显示的效果。 大家可以试一试,如果有问题可以相互交流一下。
补充
有码友说使用之后会卡顿,我把代码放进项目中测试了一下,确实在动画衔接的地方做的不够自然。因此我需要调整一下动画部分的代码
/// runtime存放动画对象,避免多次生成
- (CABasicAnimation *)getAnimation
{
CABasicAnimation * ani = objc_getAssociatedObject(self, &scrollAnimation);
if (!ani) {
ani = [CABasicAnimation animationWithKeyPath:@"position.x"];
objc_setAssociatedObject(self, &scrollAnimation, ani, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
CATextLayer * textLayer = [self getTextLayer];
CGPoint point = textLayer.position;
CGFloat lenth = textLayer.frame.size.width - self.frame.size.width;
// 起点位置
CGPoint pointSrc = CGPointMake(point.x + 20, point.y);
// 终点位置
CGPoint pointDes = CGPointMake(pointSrc.x - lenth - 30, pointSrc.y);
id toValue = [NSValue valueWithCGPoint:pointDes];
id fromValue = [NSValue valueWithCGPoint:pointSrc];
ani.toValue = toValue;
ani.fromValue = fromValue;
ani.duration = 2;
ani.fillMode = kCAFillModeBoth;
ani.repeatCount = HUGE_VALF;
// 结束后逆向执行动画
ani.autoreverses = YES;
ani.removedOnCompletion = false;
return ani;
}
代码中慎重考虑了动画的起点位置和重点位置,另外添加了每次动画后逆向执行动画的属性,让动画的过度看起来像是一个循环。这样子动画的效果确实好了很多。 还有一点,在使用的过程中发现CATextLayer在显示文字的时候,可能会出现模糊的情况,这时候只需要添加这句代码就可以解决该问题
// 不写这句可能导致layer的文字在某些情况下不清晰
layer.contentsScale = [UIScreen mainScreen].scale;
在使用过程中我发现,如果项目中使用到了系统提示框,UIAlertController这一类的东西的时候,在分类这一块会崩溃
崩溃的原因是因为NSConcreteValue不能转化成 double,NSConcreteValue这个类是我第一次见到,没弄明白是干什么的。并且查阅了资料,尝试过一些强转,也还是会崩溃。在打印中我发现,每次崩溃的时候,label的superview是UIView,再往上找一层是UIAlertControllerActionView,并且每次崩溃的时候都是这样,所以在我没有找到答案之前,我做判断,过滤了这个类的自动滚动判断,具体代码如下:
/// 判断是否需要滚动
- (BOOL)shouldAutoScroll
{
BOOL shouldScroll = false;
if (self.numberOfLines == 1) {
CGSize size = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
CGFloat stringWidth = size.width;
CGFloat labelWidth = self.frame.size.width;
if (labelWidth < stringWidth) {
shouldScroll = true;
}
}
// 加上这个判断,不然出现系统提示框的时候会崩溃
Class ModelClass = NSClassFromString(@"_UIAlertControllerActionView");
if ([self.superview.superview isKindOfClass:ModelClass]) {
shouldScroll = false;
}
return shouldScroll;
}
在判断是否需要滚动的地方,加上了这个类的过滤。就可以正常使用了。
手撸代码不易,如果对您有帮助的,可以帮忙点个赞!谢谢
代码我重新更新在GitHub上了:github.com/aYq524/Auto…