最近做项目的时候遇到一个需求,由于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
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