如何在Swift中使用MarqueeLabel?

k4ymrczo  于 2023-09-29  发布在  Swift
关注(0)|答案(8)|浏览(116)

我想知道是否有一种方法来启用文本的水平滚动,即选取框类型的文本。我用过这个库:https://github.com/cbpowell/MarqueeLabel并将“MarqueeLabel.Swift”文件添加到我的应用程序中。但到目前为止,它没有显示出我想要的字幕效果。
我是这样实现的:

class ViewController: UIViewController 
{
@IBOutlet weak var marqueeLabel: MarqueeLabel! 
override func viewDidLoad() {
    super.viewDidLoad()
        self.marqueeLabel.tag = 101
        self.marqueeLabel.type = .Continuous
        self.marqueeLabel.speed = .Duration(5)
        self.marqueeLabel.animationCurve = .EaseInOut
        self.marqueeLabel.fadeLength = 10.0
        self.marqueeLabel.leadingBuffer = 30.0
        self.marqueeLabel.trailingBuffer = 20.0
        self.marqueeLabel.restartLabel()
 }
}

我已经根据MarqueeLabel Swift中的解决方案在接口构建器中设置了自定义类,但不起作用。还是不行
所有我得到的只是一个标签显示没有选框效果(或水平文本滚动)。
P.S:我也是iOS开发的新手。另外,在实现这个库之前,我尝试使用UIScrollView和UITextView。我不能使用UIWebView,因为我试图在TVOS中实现这一点。
我的问题是:
1.我的代码哪里出错了?
1.是否有其他方法可以使用Swift显示字幕效果?
先谢了。

ars1skjm

ars1skjm1#

我使用了这段代码让我的标签像跑马灯一样滚动:

@IBOutlet weak var firstLabel: UILabel! 
override func viewDidLoad() {
    super.viewDidLoad()

    UIView.animateWithDuration(12.0, delay: 1, options: ([.CurveLinear, .Repeat]), animations: {() -> Void in
            self.firstLabel.center = CGPointMake(0 - self.firstLabel.bounds.size.width / 2, self.firstLabel.center.y)
            }, completion:  { _ in })
}

是的,成功了。

2izufjch

2izufjch2#

更新为Swift 3,不使用任何第三方库或Pod

import UIKit

class ViewController: UIViewController {

    let redLabel: UILabel = {

        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = .boldSystemFont(ofSize: 16)
        label.textColor = .red
        label.text = "The first paragraph of the body should contain the strongest argument, most significant example, cleverest illustration, or an obvious beginning point."
        return label
    }()

    let greenLabel: UILabel = {

        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = .systemFont(ofSize: 14)
        label.textColor = .green
        label.text = "The second paragraph of the body should contain the second strongest argument, second most significant example, second cleverest illustration, or an obvious follow up the first paragraph in the body."
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Marquee Label Demo"
        view.backgroundColor = .white

        view.addSubview(redLabel)
        view.addSubview(greenLabel)

        setupAutoLayout()
        startMarqueeLabelAnimation()
    }

    func startMarqueeLabelAnimation() {

        DispatchQueue.main.async(execute: {

            UIView.animate(withDuration: 10.0, delay: 1, options: ([.curveLinear, .repeat]), animations: {() -> Void in

                self.redLabel.center = CGPoint(x: 0 - self.redLabel.bounds.size.width / 2, y: self.redLabel.center.y)
                self.greenLabel.center = CGPoint(x: 0 - self.greenLabel.bounds.size.width / 2, y: self.greenLabel.center.y)

            }, completion:  nil)
        })
    }

    func setupAutoLayout() {

        redLabel.leftAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        redLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
        redLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true

        greenLabel.leftAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        greenLabel.topAnchor.constraint(equalTo: redLabel.bottomAnchor, constant: 50).isActive = true
        greenLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
    }
}

特别鸣谢:
https://stackoverflow.com/users/8303852/kartik-patel
https://stackoverflow.com/users/8388863/sid-patel
单击此处查看1演示

hpxqektj

hpxqektj3#

简单选框- Swift 4.0:

override func viewDidLoad() {
    super.viewDidLoad()
    marqueeLabel.text = " text text here!"
    _ = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(ViewController.marquee), userInfo: nil, repeats: true)
}
extension ViewController {
  @objc func marquee(){

    let str = marqueeLabel.text!
    let indexFirst = str.index(str.startIndex, offsetBy: 0)
    let indexSecond = str.index(str.startIndex, offsetBy: 1)
    marqueeLabel.text = String(str.suffix(from: indexSecond)) + String(str[indexFirst])

  }
}
qnyhuwrf

qnyhuwrf4#

在SWIFT 3中:

@IBOutlet weak var YOURLABEL: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    UIView.animate(withDuration: 12.0, delay: 1, options: ([.curveLinear, .repeat]), animations: {() -> Void in
        self.YOURLABEL.center = CGPoint(x: 0 - self.YOURLABEL.bounds.size.width / 2, y: self.YOURLABEL.center.y)
    }, completion:  { _ in })
}
moiiocjp

moiiocjp5#

由于最初的问题与tvOS有关,我刚刚错误地发现(经过几周的搜索!)tvOS 12 beta已经实现了:

只有当祖先被聚焦时(比如当我们向电影海报添加标题并滚动到它时),才能获得字幕效果,当然,如果这是目标,可以直接从TVUIKit使用TVPosterView(比如this example),但它仍然适用于单个标签。

uujelgoq

uujelgoq6#

你应该像这样使用,然后它会工作。
注意:你可能会面临性能问题,因为它在线程中使用递归,所以为了更好的性能,你应该使用CATextLayer和CAScrollLayer。

import UIKit
import SnapKit

class ViewController: UIViewController {
    
    let label = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        label.lineBreakMode = .byWordWrapping
        label.numberOfLines = 0
       
        label.text = "We couldn't turn around 'Til we were upside down I'll be the bad guy now But no, I ain't too proud I couldn't be there Even when I try You don't believe it We do this every time"
       
        view.addSubview(label)
        label.snp.makeConstraints { (make) in
           make.height.equalTo(20)
            make.top.leading.trailing.equalTo(self.view.safeAreaLayoutGuide).inset(50)
        }
      
        autoScroll()
    }
    
    @objc func autoScroll() {
        UIView.animate(withDuration: 12.0, delay: 1, options: ([.curveLinear, .repeat]), animations: {() -> Void in
            self.label.center = CGPoint(x: 0 - self.label.bounds.size.width / 2,y: self.label.center.y)
        }, completion:  { _ in
            self.autoScroll()
        })
    }
}
jckbn6z7

jckbn6z77#

在Swift 4

代码

UIView.animate(withDuration: 1.0, delay: 1, options: ([.curveLinear, .repeat]), animations: {() -> Void in
            self.marqueeLABEL.center = CGPoint(x: self.marqueeLABEL.bounds.size.width, y: self.marqueeLABEL.center.y)
        }, completion:  { _ in })
rjzwgtxy

rjzwgtxy8#

在Swift 5.8中创建自定义视图。它对我起作用

import UIKit
import SnapKit

 final class AnimatedLabel: UIView {
   private var labelText: String {
    get {
        animatedLabel.text ?? ""
    } set {
        animatedLabel.text = newValue
    }
}

private var labelTextColor: UIColor {
    get {
        animatedLabel.textColor
    } set {
        animatedLabel.textColor = newValue
    }
}

private var labelTextFont: UIFont {
    get {
        animatedLabel.font
    } set {
        animatedLabel.font = newValue
    }
}

private var isTruncated: Bool {
    guard let labelText = animatedLabel.text else { return false }
    let labelTextSize = labelText.boundingRect(
        with: CGSize(
            width: animatedLabel.frame.size.width, height: .greatestFiniteMagnitude
        ),
        options: .usesLineFragmentOrigin,
        attributes: [.font: animatedLabel.font as Any],
        context: nil
    ).size
    return labelTextSize.height > animatedLabel.bounds.size.height
}

private var scrollView: UIScrollView = UIScrollView()
private var scrollTimer: Timer?
private var isScrollingToEnd = true

private lazy var cointainerView = UIView()

private lazy var animatedLabel: UILabel = {
    let label = UILabel()
    label.lineBreakMode = .byClipping
    label.textAlignment = .left
    return label
}()

override init(frame: CGRect) {
    super.init(frame: frame)
    setupUI()
}

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

private func setupUI() {
    cointainerView.backgroundColor = .clear
    scrollView.backgroundColor = .clear
    scrollView.showsHorizontalScrollIndicator = false
    scrollView.isUserInteractionEnabled = false
    
    addSubview(cointainerView)
    cointainerView.addSubview(scrollView)
    scrollView.addSubview(animatedLabel)
    
    cointainerView.snp.makeConstraints {
        $0.left.right.top.bottom.equalToSuperview()
    }
    
    scrollView.snp.makeConstraints {
        $0.left.right.top.bottom.equalToSuperview()
    }
    
    animatedLabel.snp.makeConstraints {
        $0.top.bottom.left.right.equalToSuperview()
    }
    animatedLabel.sizeToFit()
    
    // Set the contentSize of the scrollView to enable scrolling
    scrollView.contentSize = CGSize(width: animatedLabel.bounds.width, height: animatedLabel.bounds.height)
    
    // Create a timer to scroll the label's content if isTruncated is true
    if !isTruncated {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.scrollTimer = Timer.scheduledTimer(timeInterval: 0.03, target: self, selector: #selector(self.scrollLabel), userInfo: nil, repeats: true)
        }
    }
}

@objc private func scrollLabel() {
    if isScrollingToEnd {
        scrollView.contentOffset.x += 1.0
        if scrollView.contentOffset.x >= animatedLabel.bounds.width - scrollView.bounds.width {
            isScrollingToEnd = false
        }
    } else {
        scrollView.contentOffset.x -= 1.0
        if scrollView.contentOffset.x <= 0 {
            isScrollingToEnd = true
                self.scrollLabel()
            return
        }
    }
    // If the label has reached the end, reset the content offset to scroll from the beginning
    if scrollView.contentOffset.x >= animatedLabel.bounds.width - scrollView.bounds.width {
        scrollView.contentOffset.x = 0
    }
}

func configure(text: String, textColor: UIColor, font: UIFont) {
    labelText = text
    labelTextColor = textColor
    labelTextFont = font
}

}然后你的视图控制器

import UIKit

class ViewController: UIViewController {

var animatedLabel = AnimatedLabel()

override func viewDidLoad() {
    super.viewDidLoad()
    
    animatedLabel.configure(
        text: "In publishing and graphic design, is is a long text that will scroll like a marquee.",
        textColor: .black,
        font: .systemFont(ofSize: 18)
    )

    
    
    view.addSubview(animatedLabel)
    animatedLabel.translatesAutoresizingMaskIntoConstraints = false
    
    animatedLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 150).isActive = true
    animatedLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
    animatedLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
    animatedLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
    
    
  
}

}

相关问题