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

Day 34 — I've got a solution. Is this how you do it?

Forums > SwiftUI

Dear Team,

I've achieved the three animation challenges listed here. The simplest solution I could find was to:

  1. Create three @State properties to control the three animation amounts individually.
  2. Change those three properties, and explicity animate when 'setting' the animation amounts, but not when 'resetting' the animation amounts.
  3. Using steps 1 & 2 to apply conditional modifiers to the image label.

And that's it. My base M1 Air mac didn't overheat so I'm assuming this is an efficient enough solution? Please let me know if you approve or have a better solution.

Here's my code. I've voluntarily not:

  1. Remade the UI with upgraded backgrounds. I want this simple for now.
  2. Added any animations for when user get the answer wrong. I want the movement to be muted to underscore that 'something went wrong.'
import SwiftUI

struct TitleBold: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.title.bold())
    }
}

extension View {
    func titleBold() -> some View {
        modifier(TitleBold())
    }
}

struct FlagImage: View {
    var array: [String]
    var index: Int

    var body: some View {
        Image(array[index])
            .clipShape(.capsule)
            .shadow(radius: 10)
    }
}

struct ContentView: View {

    @State private var flags = ["Estonia", "France", "Germany", "Ireland", "Italy", "Monaco", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()
    @State private var correctAnswer = Int.random(in: 0...2)

    @State private var showingAlert = false
    @State private var gameOverAlert = false
    @State private var alertTitle = ""
    @State private var alertMessage = ""

    @State private var score = 0
    @State private var questionNumber = 1

    @State private var rotationAnimationAmount = 0.0
    @State private var opacityAnimationAmount = 1.0
    @State private var scaleAnimationAmount = 1.0

    var finalScore: Int {
        (score*100)/8
    }

    var body: some View {
        NavigationStack {
            ZStack {
                Color.blue
                    .ignoresSafeArea()

                VStack(spacing: 40) {

                    VStack {
                        Text("Tap the flag of")
                            .font(.title2)
                        Text(flags[correctAnswer])
                            .titleBold()
                    }

                    VStack(spacing: 30) {
                        ForEach(0..<3) { num in
                            Button {
                                flagTapped(num)
                            } label: {
                                FlagImage(array: flags, index: num)
                                    .rotation3DEffect(.degrees(num == correctAnswer ? rotationAnimationAmount : 0), axis: (x:0, y:1, z:0))
                                    .opacity(num != correctAnswer ? opacityAnimationAmount : 1)
                                    .scaleEffect(num != correctAnswer ? scaleAnimationAmount : 1)
                            }
                        }
                    }

                    VStack {
                        Text("\(questionNumber)/8")
                            .font(.footnote)
                        Text("Score: \(score)")
                            .font(.callout.bold())
                    }

                }
                .alert(alertTitle, isPresented: $showingAlert) {
                    Button("Ok") {nextQuestion()}
                } message: {
                    Text(alertMessage)
                }
                .alert(alertTitle, isPresented: $gameOverAlert) {
                    Button("Cancel") {}
                    Button("New Game") {newGame()}
                } message: {
                    Text(alertMessage)
                }
            }
        }
    }

    func flagTapped(_ buttonNum: Int) {
        if questionNumber < 9 {
            if buttonNum == correctAnswer {
                withAnimation {
                    rotationAnimationAmount += 360.0
                    opacityAnimationAmount = 0.25
                    scaleAnimationAmount = 0.85
                }
                alertTitle = "Correct!"
                alertMessage = "You've earned 1 point"
                score += 1
            } else {
                alertTitle = "Oops"
                alertMessage = "That's the flag of \(flags[buttonNum])."
            }
            showingAlert = true
        }
    }

    func nextQuestion() {
        rotationAnimationAmount = 0.0
        opacityAnimationAmount = 1.0
        scaleAnimationAmount = 1.0

        if questionNumber == 8 {
            alertTitle = "Game Over"
            alertMessage = "You scored \(finalScore)%"
            gameOverAlert = true
        } else {
            questionNumber += 1
            flags.shuffle()
            correctAnswer = Int.random(in: 0...2)
        }
    }

    func newGame() {
        questionNumber = 0
        score = 0
        nextQuestion()
    }
}

#Preview {
    ContentView()
}

Looking forward to hearing from y'all.

Best, Ara.

   

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.

Click to save your free spot 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.