Swift 跑马灯(可放在轮播上的跑马灯,每次“自动/手动”切换回到初始位置)

话不多说,直接上代码
  • 文字内容超出文本跑动
  • 文字内容未超出文本不跑动
import UIKit

class MarqueeText: UIView {
    public var text: String? {
        willSet {
            nameLabel?.text = newValue
            setNeedsLayout()
        }
    }

    public var textColor: UIColor = UIColor(hex: 0xffffff) {
        willSet {
            nameLabel?.textColor = newValue
        }
    }

    public var textFont: UIFont = .systemFont(ofSize: 13, weight: .medium) {
        willSet {
            nameLabel?.font = newValue
        }
    }

    private weak var displayLink: CADisplayLink?
    
    var duration: TimeInterval = 0
    
    // 滚动复位
    var isZero : Bool?{
        didSet{
            if isZero == true {
                duration = 0
                scrollView?.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
            }
        }
    }

    /// 是否向左滚动标记
    private var isLeft: Bool = true

    /// 是否需要滚动标记
    private var isCanRun: Bool = true

    private weak var nameLabel: UILabel?
    private weak var scrollView: UIScrollView?
    private weak var leftGlassLayer: CAGradientLayer?
    private weak var rightGlassLayer: CAGradientLayer?

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clear
        initSubviews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        displayLink?.isPaused = true
    }

    override func touchesEnded(_ touches: Set, with event: UIEvent?) {
        if isCanRun {
            displayLink?.isPaused = false
        }
    }

    override func touchesCancelled(_ touches: Set, with event: UIEvent?) {
        if isCanRun {
            displayLink?.isPaused = false
        }
    }

    deinit {
        self.displayLink?.invalidate()
        self.displayLink = nil
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        let textSize = self.textSize(text: nameLabel?.text ?? "", font: UIFont.systemFont(ofSize: 13, weight: .medium), height: 18)
        let margin: CGFloat = 0
        let textWith = textSize.width + margin * 2
        scrollView?.frame = bounds
        scrollView?.backgroundColor = UIColor.clear
        scrollView?.contentSize = CGSize(width: 0, height: textWith)
        nameLabel?.frame = CGRect(x: 0, y: 0, width: textWith, height: textSize.height)
        nameLabel?.centerY = self.centerY
        duration = 0
        nameLabel?.backgroundColor = UIColor.clear
        isCanRun = textWith > width
        displayLink?.isPaused = width >= textWith

        leftGlassLayer?.isHidden = width >= textWith
        rightGlassLayer?.isHidden = width >= textWith
        leftGlassLayer?.frame = CGRect(x: 0, y: 0, width: 25, height: height)
        rightGlassLayer?.frame = CGRect(x: width - 25, y: 0, width: 25, height: height)
    }
    
    func textSize(text: String,  font: UIFont, height: CGFloat) -> CGSize {
        return text.boundingRect(with:CGSize(width:CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: [.font:font], context:nil).size
    }

    private func initSubviews() {
        let scrollView = UIScrollView()
        scrollView.isUserInteractionEnabled = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        addSubview(scrollView)
        self.scrollView = scrollView

        let nameLabel = UILabel()
        nameLabel.textAlignment = .center
        nameLabel.font = textFont
        nameLabel.textColor = textColor
        scrollView.addSubview(nameLabel)
        self.nameLabel = nameLabel

        let displayLink = CADisplayLink(target: self, selector: #selector(timerEvent))
        displayLink.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
        displayLink.isPaused = true
        self.displayLink = displayLink

        let leftGlassLayer = CAGradientLayer()
        leftGlassLayer.startPoint = .zero
        leftGlassLayer.endPoint = CGPoint(x: 1, y: 0)
//        leftGlassLayer.colors = [UIColor.colorWithHexString(color: "6DD781").cgColor, UIColor.colorWithHexString(color: "6DD781", alpha: 0).cgColor]
        leftGlassLayer.colors = [UIColor.clear.cgColor]
        layer.addSublayer(leftGlassLayer)
        self.leftGlassLayer = leftGlassLayer

        let rightGlassLayer = CAGradientLayer()
        rightGlassLayer.startPoint = .zero
        rightGlassLayer.endPoint = CGPoint(x: 1, y: 0)
//        rightGlassLayer.colors = [UIColor.colorWithHexString(color: "6DD781", alpha: 0).cgColor, UIColor.colorWithHexString(color: "6DD781").cgColor]
        rightGlassLayer.colors = [UIColor.clear.cgColor]
        layer.addSublayer(rightGlassLayer)
        self.rightGlassLayer = rightGlassLayer
    }

    var i = 0
    @objc private func timerEvent() {
        if duration == 0 {
            if i == 0 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [self] in
                    abcd()
                    i = 0
                }
                i = 1
            }

        } else {
            abcd()
        }
    }

    /// 定时器事件
    func abcd() {
        let maxWith = (nameLabel?.width ?? 0) - width + 40
        let scale: TimeInterval = 1.5
        if duration < 0 {
            isLeft = false
            duration += scale
        } else if duration >= 0 && duration <= TimeInterval(maxWith) {
            if isLeft {
                duration -= scale
            } else {
                duration += scale
            }
        } else {
            isLeft = true
            duration = 0
        }

        scrollView?.setContentOffset(CGPoint(x: duration, y: 0), animated: false)
    }
}


  • 使用
var titleLabel = MarqueeText()

titleLabel.text = "跑马灯,跑起来"


// 如果是在上下翻转的轮播上添加横向的跑马灯,在轮播切换的方法里面添加:  
titleLabel.isZero = true

你可能感兴趣的:(Swift 跑马灯(可放在轮播上的跑马灯,每次“自动/手动”切换回到初始位置))