TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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.

2      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.