我一直在网上搜索我的问题的答案,但似乎没有任何解决方案。我有一个 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/