UILabel显示不全时循环滚动显示,利用Runtime黑魔法全局修改

最近做项目的时候遇到一个需求,由于App兼容的语言类型太多,导致App内很多标签显示的文字不全,这时候需要滚动去显示。需求类似下面这个样子。


滚动效果展示

思考

1.整个App的label去做一个滚动显示,首先要考虑到性能问题,性能问题的话就不考虑使用UIView层去实现该效果,因此,文字滚动层考虑用Layer去处理。
2.能够影响到文本显示和是否能完全显示文本的属性有text、frame、font、textColor,因此我们需要对这几项属性进行处理。

在设置text的属性的时候,我们需要判断text的长度是否大于label的长度, 如果大于label的长度,我们需要将text文本处理到layer层,并且做滚动动画。在这是framefont的时候我们需要重新做该判断,因为这两个属性影响了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就能自动判断并且实现滚动显示的效果。
大家可以试一试,如果有问题可以相互交流一下。

手撸代码不易,如果对您有帮助的,可以帮忙点个赞!谢谢

代码地址:https://github.com/aYq524/AutoScrollLabel

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,734评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,931评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,133评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,532评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,585评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,462评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,262评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,153评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,587评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,792评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,919评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,635评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,237评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,855评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,983评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,048评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,864评论 2 354

推荐阅读更多精彩内容