编辑:我实际上想为 textColor
属性设置动画。我认为它与 backgroundColor
的解决方案相同,但显然不是因为 textColor
在 layer
中不可用。我找到了这个 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)
})
}
奇怪的行为
最佳答案
试试下面改变的方法:
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/