[英]Animating UILabel textColor property with UIViewPropertyAnimator
我有一個看起來很簡單的問題,但我還沒有找到解決方案。
我使用UIViewPropertyAnimator
和 slider 為帶有標簽的視圖設置動畫,以手動調整動畫器的fractionComplete
屬性。
在我動畫的視圖中,我有一個 UILabel 並且我想動畫它的textColor
。
我發現SO 答案建議像這樣為textColor
設置動畫:
UIView.transition(with: yourLabel, duration: 0.3, options: .transitionCrossDissolve, animations: {
self.yourLabel.textColor = .red
}, completion: nil)
但是,對我來說這不起作用,因為我希望 animation 根據我為動畫師設置的fractionComplete
繼續。
正如評論中所說, textColor
屬性不能動畫。 但是,有一種稱為顏色插值的技術,它可能是一個很好的解決方法。
您可以在此線程中找到多種解決此問題的方法,但是,我也為您提供了一種解決方案:
extension UIColor {
var components: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
let components = self.cgColor.components!
switch components.count == 2 {
case true :
return (r: components[0], g: components[0], b: components[0], a: components[1])
case false:
return (r: components[0], g: components[1], b: components[2], a: components[3])
}
}
static func interpolate(from fromColor: UIColor, to toColor: UIColor, with progress: CGFloat) -> UIColor {
let fromComponents = fromColor.components
let toComponents = toColor.components
let r = (1 - progress) * fromComponents.r + progress * toComponents.r
let g = (1 - progress) * fromComponents.g + progress * toComponents.g
let b = (1 - progress) * fromComponents.b + progress * toComponents.b
let a = (1 - progress) * fromComponents.a + progress * toComponents.a
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
然后,您只需在滑塊值更改時調用的 function 中執行此操作:
@objc func sliderChanged(_ sender: UISlider) {
animator.fractionComplete = CGFloat(sender.value)
yourLabel.textColor = UIColor.interpolate(from: fromColor, to: toColor, with: sender.value)
}
您不是在為textColor
設置動畫,而是在每次調用sliderChanged
時將其更改為不同的顏色,但是這種變化看起來是漸進的,並且不會從您的起始顏色跳到您的第二種顏色,所以我認為它應該達到您想要的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.