ios - 在同一 UILabel 上的两个不同文本之间重复淡入/淡出

标签 ios swift animation

我一直在网上搜索我的问题的答案,但似乎没有任何解决方案。我有一个 UILabel,其中包含两个可互换的图标(来自 FontAwesome)。我想创建一个动画,它反复将 UILabels 文本从一个更改为另一个。

到目前为止,我所拥有的是一个一次又一次调用自身的动画。它在模拟器上看起来不错,但是当我在手机上运行它时,它并没有按照我想要的方式运行。我似乎快到了,但我的代码在淡出时会产生某种闪光

func animateLabel() {
    self.runningPersonLabel.text = self.runningPersonLabel.text == "ICON 1" ? "ICON 2" : "ICON 1"
    self.runningPersonLabel.sizeToFit()
    self.runningPersonLabel.center = modalContainer.boundsCenter
    self.runningPersonLabel.frameTop = titleLabel.frameBottom + 40

    UIView.animate(withDuration: 2, delay: 0, options: [.autoreverse], animations: {
        self.runningPersonLabel.alpha = 1.0
    }, completion: { finished in
        self.runningPersonLabel.alpha = 0.0
        self.animateLabel()
    })
}

最佳答案

试试这个类:

import UIKit

@IBDesignable class FadingLabel: UILabel
{
    // The secondary text
    @IBInspectable var secondaryText:String?
    var primaryText:String?

    // Animation time, is divided by 2
    @IBInspectable var animationTime:TimeInterval = 1

    // Set this flag to true to stop animation
    var stop = true

    // Start the animation
    func startAnimating()
    {
        stop = false
        if primaryText == nil
        {
            primaryText = self.text
        }

        fadeAnim()
    }

    // Stop the animation
    func stopAnimating(_ sender: UIButton)
    {
        stop = true
    }

    @objc private func fadeAnim()
    {
        if stop
        {
            return
        }

        // Fade out
        UIView.animate(withDuration: animationTime / 2, animations: {
            self.alpha = 0
        }) { (complete) in
            UIView.animate(withDuration: self.animationTime / 2, animations: {
                if self.text == self.primaryText
                {
                    self.text = self.secondaryText
                }
                else
                {
                    self.text = self.primaryText
                }

                self.alpha = 1

            }, completion: { (complete2) in
                self.fadeAnim()
            })
        }
    }
}

用法:

  • 在你的 View Controller 中放置一个标签;
  • 设置标签类为FadingLabel;
  • 在 Storyboard检查器中设置辅助文本和动画时间
  • 根据需要调用方法 startAnimating 或 stopAnimating。

关于ios - 在同一 UILabel 上的两个不同文本之间重复淡入/淡出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57539886/

相关文章:

angularjs - 在Angular 1.4+中页面加载时ng-repeat交错动画

java - 油漆组件 : paint different geometric shapes after delay each time

ios - 防止键盘作为第一响应者与文本字段一起出现

ios - 如何显示 UITableViewCell 的自定义 UIMenuItem?

ios - Swift - webView 顶部的 iAd 横幅

Swift 运行时文档

swift - 计算 MKMapView 中 MKPolygon 的面积

ios - Swift:JSON 似乎没问题,但我仍然收到 Cocoa 错误 3840

iOS - 是否可以缓存分块的 HTTP 响应?

javascript - webkit 中的 CSS 动画在自动之前变为零