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

Day 34. Animation Challenge.

Forums > 100 Days of SwiftUI

Hey guys, this challenge is almost broke me apart. Want to share with you my approach. {Spoiler Alert! - there will be a solution}

What are the steps I've taken? First, I've banged my head for many hours. (this is not necessary step at all).

Decide clearly how you want to Animate the View. In my case it was how to Animate the wrong answer of player. Why we're struggling here mostly? Because of the game logic, and not because we don't know how to animate!

  1. Where happens all the animation action? When the button is pressed! Button(action: { .... here goes only and only the number of the button we touched!!! and nothing else. So we'll use this exactly for variable wrongAnswer to remember what is the wrong answer that user has touched and no other wrong answer.

The problem I met is dealing with ForEach.

  1. If users answers right - we want to twist the right answer, and set up opacity of wrong answers. But, opacity modifier should be applied only after user pressed the button, and not before. So, in action we change the 'permission' canAnimateRightAnswer to true.

  2. We set up amount values, that describe the final state of the views, animations will make the transition.

  3. Then there're modifiers with their conditions.

  4. After alert pops out, on dismiss it calls a function askQuestion() , where I refresh all the parameters again to intial state. In my case the refresh is in function stopAnimation()

  5. The type of animation used here is - explicit animation (I guess so).

In the beginnning, I tried to encapsulate logic in FlagImage struct (that's why part of code is there) , but abonded this idea.

struct FlagImage: View {
    var image: String
    var isCorrectAnswer: Bool
    var animationAmount: Double

    var body: some View {
        Image(image)
            .renderingMode(.original)
            .clipShape(Capsule())
            .overlay(Capsule().stroke(Color.black, lineWidth: 1))
            .shadow(color: .black, radius: 2)

            //.opacity(isCorrectAnswer ? 1 : 0.25)
            .rotation3DEffect(isCorrectAnswer ? .degrees(Double(animationAmount)) : .zero,
                    axis: (x: 0.0, y: 1.0, z: 0.0)
                    )

    }

}

//MARK:-View

struct ContentView: View {
    @State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()
    @State private var correctAnswer = Int.random(in: 0...2)
    @State private var showingScore = false
    @State private var scoreTitle = ""
    @State private var userScore = 0
    @State private var scoreChange = ""

    @State private var wrongAnswer: Int? = nil
    @State private var animationAmountForRight = 0.0
    @State private var animationAmountForWrong = 0.0
    @State private var backgroundAmount = 0.0
    @State private var canAnimateRightAnswer = false

    var body: some View {
        ZStack {
            LinearGradient(gradient: Gradient(colors: [.blue,.purple]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)

            VStack(spacing: 30) {
                VStack {
                    Text("Tap the flag of")
                        .foregroundColor(.white)

                    Text(countries[correctAnswer])
                        .foregroundColor(.white)
                        .font(.largeTitle)
                        .fontWeight(.black)

                }

                ForEach(0 ..< 3) { number in
                    Button(action: {
                        self.flagTapped(number)

                        // here goes only and only the number of the button we touched!!! (i.e. in action section)
                        if number == correctAnswer {
                            withAnimation(.easeOut(duration: 1)) {
                                animationAmountForRight += 360
                                canAnimateRightAnswer = true
                            }

                        } else {
                            wrongAnswer = number
                            withAnimation(Animation.easeOut(duration: 0.25).repeatCount(6)) {
                                backgroundAmount += 1
                                animationAmountForWrong += 60
                            }
                        }

                    }, label: {
                        FlagImage(image: self.countries[number].lowercased(), 
                            isCorrectAnswer: (number == correctAnswer), 
                            animationAmount: Double(animationAmountForRight))
                    })

                    .opacity(number != correctAnswer && canAnimateRightAnswer ? 0.25 : 1)
                    .rotation3DEffect(number == wrongAnswer ?
                                        .degrees(Double(animationAmountForWrong - 30)) : .zero,
                                      axis: (x: 0.0, y: 1.0, z: 0.0)

                        )

                    .padding()

                    .background(number == wrongAnswer ? 
                               Color.red.opacity(Double(backgroundAmount)) : Color.blue.opacity(0))

                }

                Text("Score: \(userScore)")
                    .foregroundColor(.white)

                Spacer()
            }
        } .alert(isPresented: $showingScore, content: {
            Alert(title: Text(scoreTitle), message: Text("Your score is \(userScore) \(scoreChange)"), dismissButton: .default(Text("Continue")) {

                    self.askQuestion()
            })

        })

    }

    func flagTapped(_ number: Int) {
        if number == correctAnswer {
            scoreTitle = "Correct"
            userScore += 1
            if userScore > 1 {
                scoreChange = "(+1)"
            } else {
                scoreChange = ""
            }

        } else {
            scoreTitle = "Wrong! That's the flag of \(countries[number])"

            if userScore > 0 {
                userScore -= 1
                scoreChange = "(-1)"
            } else {
                scoreChange = ""
            }
        }

        showingScore = true
    }

    func stopAnimation() {
        animationAmountForRight = 0
        animationAmountForWrong = 0
        backgroundAmount = 0
        canAnimateRightAnswer = false
    }

    func askQuestion() {
        countries.shuffle()
        correctAnswer = Int.random(in: 0...2)
        stopAnimation()
        wrongAnswer = nil
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.