问题描述
我一直在尝试对UI的各个部分进行动画处理,但是似乎您无法为SwiftUI Text的frontantColor设置动画?我想在状态改变时平稳地切换某些文本的颜色.如果我为文本"周围的视图设置背景颜色动画,则此方法很好,但是前景色不起作用.有没有人有幸为这样的变化做动画?不确定这是Xcode beta错误还是预期的功能...
I've been trying to work on animating various parts of the UI, but it seems as though you can't animate a SwiftUI Text's foregroundColor? I want to switch the color of some text smoothly when a state changes. This works fine if I animate the background color of the Text's surrounding view, but foreground color does not work. Has anyone had any luck animating a change like this? Unsure if this is an Xcode beta bug or it's intended functionality...
Text(highlightedText)
.foregroundColor(color.wrappedValue)
.animation(.easeInOut)
// Error: Cannot convert value of type 'Text' to closure result type '_'
推荐答案
有一个更简单的方法,该方法借鉴了Apple的动画视图和过渡"教程代码. HikeGraph中的GraphCapsule实例化证明了这一点.
There is a much easier way, borrowing from Apple's "Animating Views and Transitions" tutorial code. The instantiation of GraphCapsule in HikeGraph demonstrates this.
foregroundColor
不能动画,而colorMultiply
可以动画.将前景色设置为白色,然后使用colorMultiply设置所需的实际颜色.要从红色动画为蓝色:
While foregroundColor
cannot be animated, colorMultiply
can. Set the foreground color to white and use colorMultiply to set the actual color you want. To animate from red to blue:
struct AnimateDemo: View {
@State private var color = Color.red
var body: some View {
Text("Animate Me!")
.foregroundColor(Color.white)
.colorMultiply(self.color)
.onTapGesture {
withAnimation(.easeInOut(duration: 1)) {
self.color = Color.blue
}
}
}
}
struct AnimateDemo_Previews: PreviewProvider {
static var previews: some View {
AnimateDemo()
}
}
这篇关于SwiftUI:动画文本颜色-前景色()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!