编辑:我真的想动画textColor属性.我认为它与backgroundColor的解决方案相同,但显然不是因为textColor在图层中不可用.我找到了这个
here的解决方案.
我试图每隔一秒随机改变UILabel背景的颜色.我使用的代码在常规视图上工作正常,但是当我在标签上调用它时迭代速度太快.它好像持续时间的动画不会在标签上占用任何时间.知道为什么会这样吗?我实际上想要更改标签文本颜色,这就是为什么它在标签上的重要性.
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)
})
}
请尝试更新标签textColor动画的答案:
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)
}