You need to enable JavaScript to run this app. SwiftUI实现点击正确国旗沿Y轴360度旋转动画问题求解
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI实现点击正确国旗沿Y轴360度旋转动画问题求解

SwiftUI 国旗答题动画效果修复方案

问题根源

  • 你将视图修饰符rotation3DEffect和Button视图错误写在了业务函数flagTapped中,SwiftUI 中只有写在body内的视图和修饰符才会渲染生效,业务函数中写视图代码不会产生任何作用
  • 你使用了全局统一的animationAmount变量,所有国旗都绑定同一个动画值,自然触发时所有国旗会同时旋转
  • 缺少状态变量记录用户点击的正确国旗索引,无法判断应该给哪个国旗应用旋转动画

修复后的完整代码

import SwiftUI

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 score = 0
    @State private var animationAmount = 0.0
    // 新增:记录点击正确的国旗索引
    @State private var tappedCorrectFlag: Int? = nil

    var body: some View {
        ZStack {
            LinearGradient(gradient: Gradient(colors: [.blue, .black]),
                           startPoint: .top, endPoint: .bottom)
            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)
                    }) {
                        Image(self.countries[number])
                            .renderingMode(.original)
                            .clipShape(Capsule())
                            .overlay(Capsule().stroke(Color.black, lineWidth: 1))
                            .shadow(color: .black, radius: 2)
                            // 仅给点击正确的国旗应用旋转动画
                            .rotation3DEffect(.degrees(number == tappedCorrectFlag ? animationAmount : 0), axis: (x: 0, y: 1, z: 0))
                    }
                }
                Spacer()
            }
        }
        .alert(isPresented: $showingScore) {
            Alert(title: Text(scoreTitle), message: Text("Your score is \(score)"), dismissButton: .default(Text("Continue")) {
                self.askQuestion()
            })
        }
    }

    func flagTapped(_ number: Int) {
        if number == correctAnswer {
            scoreTitle = "Correct"
            score += 100
            // 标记当前点击的是正确国旗
            tappedCorrectFlag = number
            // 直接触发动画
            withAnimation(.easeInOut(duration: 1)) {
                self.animationAmount += 360
            }
        } else {
            scoreTitle = "Wrong. This was the flag of \(countries[number])"
            score -= 100
        }
        showingScore = true
    }

    func askQuestion() {
        countries.shuffle()
        correctAnswer = Int.random(in: 0...2)
        // 重置标记,避免下次出题残留动画
        tappedCorrectFlag = nil
    }
}

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

内容的提问来源于stack exchange,提问作者Paul T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 08:30:02