ios - 使用 UILabel 的持续时间动画表现得很奇怪

标签 ios swift animation uilabel

编辑:我实际上想为 textColor 属性设置动画。我认为它与 backgroundColor 的解决方案相同,但显然不是因为 textColorlayer 中不可用。我找到了这个 here 的解决方案.

我正在尝试每隔一秒随机更改 UILabel 的背景颜色。我使用的代码在常规 View 中运行良好,但在标签上调用时迭代速度太快。好像带有持续时间的动画没有在标签上花费任何时间。知道这是为什么吗?我实际上想更改标签文本颜色,这就是它在标签上起作用的重要性。

colorChanges(v: lbl) // TOO FAST!
colorChanges(v: someView) // PERFECT
colorChanges(v: self.view) // PERFECT

动画代码

func colorChanges(v: UIView) {
    UIView.animate(withDuration: 1.0, animations: {
        v.backgroundColor = UIColor(displayP3Red: CGFloat(arc4random()) / CGFloat(UInt32.max), green: CGFloat(arc4random()) / CGFloat(UInt32.max), blue: CGFloat(arc4random()) / CGFloat(UInt32.max), alpha: 1.0)
    }, completion: {
        (value: Bool) in
        self.colorChanges(v: v)
    })
}

奇怪的行为

enter image description here

最佳答案

试试下面改变的方法:

func colorChanges(v: UIView) {
    UIView.animate(withDuration: 1.0, animations: {
            v.layer.backgroundColor = UIColor(displayP3Red: CGFloat(arc4random()) / CGFloat(UInt32.max), green: CGFloat(arc4random()) / CGFloat(UInt32.max), blue: CGFloat(arc4random()) / CGFloat(UInt32.max), alpha: 1.0).cgColor
        }, completion: { [weak self]
            (value: Bool) in
            self?.colorChanges(v: v)
        })
    }

请尝试更新标签文本颜色动画的答案:

        UIView.transition(with: v, duration: 1.0, options:.transitionCrossDissolve, animations: {
            v.backgroundColor = UIColor(displayP3Red: CGFloat(arc4random()) / CGFloat(UInt32.max), green: CGFloat(arc4random()) / CGFloat(UInt32.max), blue: CGFloat(arc4random()) / CGFloat(UInt32.max), alpha: 1.0)

            if let label = v as? UILabel {
                label.textColor = UIColor(displayP3Red: CGFloat(arc4random()) / CGFloat(UInt32.max), green: CGFloat(arc4random()) / CGFloat(UInt32.max), blue: CGFloat(arc4random()) / CGFloat(UInt32.max), alpha: 1.0)
            }
        }) { [weak self] (success) in
            self?.colorChanges(v: v)
        }

关于ios - 使用 UILabel 的持续时间动画表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50550326/

相关文章:

ios - 如何确保 OBJ 模型以正确的方向显示?

ios - 如何在 swift 中迭代未知数量的嵌套级别的嵌套字典?

ios - swift : scroll the view up when keyboard shows

java - 使用动画绘制显示动画

android - 弹跳按钮 flutter

iOS 动画 : CADisplayLink vs CAShapeLayer

ios - 使用 UIWebView 在 iOS 应用程序中登录 Instagram 时出错

ios - _OBJC_CLASS_$_ScringoAgent”,引用自 :

ios - 如何调整操作表的大小? objective-c

android - 动画 ListView 项目对多行生效