NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

WithAnimation location in code question

Forums > 100 Days of SwiftUI

Hello,

Working through Project 6 and refactoring the Guess The Flag game I was wondering if someone could explain why one code works and one doesn't. I had to find other peoples solutions on GitHub unfortuntely I couldn't figure this one out on my own. The ternanry operator on the animation blew my mind. I get it now.

This code below works and animates the correct flag. What I found to make it work in my code is that the winAnimation has to be below the function call of flagTapped

ForEach(0..<3) { number in
                        Button{

                            // Flag was tapped
                            flagTapped(number)

                            withAnimation{
                                isRotating += 360
                                scaleAmount = 0.5
                            }

                            gameQuestionCount += 1

                            if gameQuestionCount >= 8 {
                                gameComplete = true
                            }
                        } label: {
                            FlagImage(flagString: countries[number])
                        }
                        // Project 6 challenge for rotating the correct flag
                        .rotation3DEffect(.degrees(number == buttonNumber ? isRotating : 0.0),
                                          axis: (x:0, y: 1, z: 0 ))
                        // Scale incorrect answers to 0.5
                        .scaleEffect(number == correctAnswer ? 1 : scaleAmount, anchor: .center)

If the withAnimation is above the function call the wrong flag will get animated. Usually the animation is off by one. What I mean by that is if the first correct answer is button 0 nothing rotate. The next question if the correct flag is button 1 button 0 rotates and so on.

Can anyone eplain why this is?

Thank you.

   

Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

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

Reply to this topic…

You need to create an account or log in to reply.

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.