首页 > 解决方案 > 数组没有被洗牌并且屏幕被重绘

问题描述

正如你所看到的,我有一个函数应该对我的国家数组进行洗牌,因为@State我的理解是应该重绘屏幕,因为 Swift UI 是声明性的......但我没有得到这种行为。我得到一个弹出窗口,但在取消它时,新的标志集不会被重绘。

struct ContentView: View {
    @State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "USA"].shuffled()
    
    @State private var correctAnswer = Int.random(in: 0...2)
    @State private var country = ""
    @State private var showingScore = false
    @State private var scoreTitle = ""
    @State private var userScore = 0
    
    func flagTapped(_ flag: Int) {
        if flag == correctAnswer {
            scoreTitle = "Correct"
            userScore += 1
        } else {
            scoreTitle = "Wrong thats the flag for \(countries.self)"
            userScore -= 1
        }
        showingScore = true
    }
    
    
    func askQuestion() {
        countries.shuffled()
        correctAnswer = Int.random(in: 0...2)
    }
  

    
    
    var body: some View {
 
        
        
        ZStack {
            RadialGradient(gradient: Gradient(colors: [Color.blue, Color.black ]), center: .center, startRadius: /*@START_MENU_TOKEN@*/5/*@END_MENU_TOKEN@*/, endRadius: 600).edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
            
                .alert(isPresented: $showingScore) {
                    Alert(title: Text(scoreTitle), message: Text("Your Score is \(userScore)"), dismissButton: .default(Text("Continue")) { self.askQuestion() } )
                }
        VStack(spacing: 30) {
            VStack {
                Text("Tap the flag of")
                    .foregroundColor(.white)
                    .shadow(radius: /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/)
                Text(countries[correctAnswer])
                    .foregroundColor(.yellow)
                    .font(.largeTitle)
                    .shadow(radius: /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/)
                
                Text("Your Score is \(userScore)")
                    .foregroundColor(.white)
                    .shadow(radius: /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/)
                
            }
            
            ForEach(0..<3) { flag in
                Button(action : {
                    flagTapped(flag)
                }) {
                    Image(self.countries[flag])
                        .renderingMode(.original)
                        .clipShape(RoundedRectangle(cornerSize: /*@START_MENU_TOKEN@*/CGSize(width: 20, height: 10)/*@END_MENU_TOKEN@*/))
                        .shadow(radius: /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/)
                    }
                }
            }
        }
    }
}

标签: swiftswiftui

解决方案


这是一个修复

func askQuestion() {
    countries = countries.shuffled()        // << assign !!
    correctAnswer = Int.random(in: 0...2)
}

推荐阅读