100 Days of SwiftUI

100 Days of SwiftUI - Day 22 猜旗项

2020-10-20  本文已影响0人  星星星宇

1.给猜旗项目添加一个用户得分

添加得分后的效果图
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 scoreTitle = ""
    @State private var scoreContent = Text("")
    @State private var showingScore = false
    @State private var score = 0

    var body: some View {
        
        ZStack {
            LinearGradient(gradient: Gradient(colors: [.blue, .black]), 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: {
                        flagTappped(number)
                    }, label: {
                        Image(countries[number])
                            .renderingMode(.original)
                            .clipShape(Capsule())
                            .overlay(Capsule().stroke(Color.black, lineWidth: 1.0))
                            .shadow(color: .black, radius: 2)
                    })
                }
                
                Text("Score: \(score)")
                        .foregroundColor(.white)
                
                Spacer()
            }
        }
        .alert(isPresented: $showingScore, content: {
            Alert(title: Text(scoreTitle), message: scoreContent, dismissButton: Alert.Button.default(Text("Continue"), action: {
                askQuestion()
            }))
        })
    }
    
    func flagTappped(_ number: Int) {
        if number == correctAnswer {
            scoreTitle = "Correct"
            score += 1
            scoreContent = Text("Your score is \(score)")
        } else {
            scoreTitle = "Wrong!"
            scoreContent = Text("That's the flag of \(countries[number])")
        }
        showingScore = true
    }
    
    func askQuestion() {
        countries = countries.shuffled()
        correctAnswer = Int.random(in: 0...2)
    }
}
上一篇下一篇

猜你喜欢

热点阅读