UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

WithAnimation not working as expected when property is existing in separate View

Forums > SwiftUI

I have two distinct Views using a single property that's part of my @EnvironmentObject. One having a Button that uses withAnimation to toggle the property and then another View, in a separate file, that checks the affected property. WithAnimation is great but I noticed that when the property that is being toggled within withAnimation is used in a separate View that View will render first before the toggle completes.

Is there a way to get around this. My Views do not have.a parent child hierarchy so I cannot pass down the property.

2      

One thing to remember about View state variables and animation: Variables change immediately. Animations are rendered over a time period.

You may have a variable that stores an oven's temperature. Maybe that temperature is bound to a graphical element in your user interface. You want the temperature guage to have a nice smooth transition whenever the oven's temperature changes.

Somewhere in your code you change the temperature from 200 degrees to 350 degrees. So your animation should smoothly change between those two graphical states, perhaps even changing colors.

Remember, in your program, the variable instantly changes from 200 to 350. However, the iOS graphics engine takes a snapshot of the current look, generates the final look, then creates a number of inbetween frames to adequately create a pleasing animation over the duration you specified.

The animation from 200 to 350 may take 3 or 4 seconds to watch. But the variable changed before the animation even started. The changed variable may be kicking off the change in your second view?

That being said, it's hard to diagnose your issue without seeing code. Can you simplify your two views? Take out everything but the button and desired animations and post simplified code here? When you say "toggle" I think "boolean".

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.