[英]SwiftUI prevent animation when updating State
I have a view, that displays an image and when I scroll, this image changes in opacity, scale and offset.我有一个视图,它显示一个图像,当我滚动时,这个图像的不透明度、比例和偏移量会发生变化。
Image(...)
.resizable()
.opacity(artworkOpacity)
.scaleEffect(artworkScale)
.offset(artworkOffset)
This is defined in struct MyView: View {... }
.这是在
struct MyView: View {... }
中定义的。 At the app level I set在我设置的应用级别
MyView()
.animation(.default)
.transition(someTransition)
This works well, except for when updating those 3 state variables (opacity, scale and offset), those are animated too!这很好用,除了更新这 3 个 state 变量(不透明度、比例和偏移)时,这些也是动画的! Adding
.animation(nil)
at the end fixes that, however the transition breaks, the image is the only view that is not transitioning properly.在最后添加
.animation(nil)
修复了这个问题,但是过渡中断,图像是唯一没有正确过渡的视图。
How can I make the animation only happen during a transition and not while updating state?如何使 animation 仅在过渡期间发生,而不是在更新 state 时发生?
I tried with various combinations of enabling and disabling the animation in that view as well as with withAnimation(nil) { // update State }
我尝试了在该视图中启用和禁用 animation 的各种组合以及
withAnimation(nil) { // update State }
Thanks!谢谢!
It's hard to tell exactly what's going on without the full code, but you can add Animation directly to the Transition instead of the whole object.如果没有完整的代码,很难准确判断发生了什么,但您可以将 Animation 直接添加到转换中,而不是整个 object。
.transition(AnyTransition.move(edge: .bottom).animation(.easeInOut))
I figured it out!我想到了!
There is .animation(..., value: ...)
, where animation is only added to the view, if the value (which is an equatable), has changed.有
.animation(..., value: ...)
,其中 animation 仅添加到视图中,如果值(这是一个等价的)已经改变。 So the entire view is not affected by the animation, unless the state that defines the current view changes and transition begins.因此整个视图不受 animation 的影响,除非定义当前视图的 state 发生变化并开始转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.