import SwiftUI
struct ContentView: View {
@State var showingScore = false
@State var scoreTitle = ""
@State var countries = ["Estonia", "France", "Germany","Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()//须添加图片资源
@State var correctAnswer = Int.random(in: 0...2)
var body: some View {
ZStack {
LinearGradient(gradient: Gradient(colors: [Color.blue, Color.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: {
flagTapped(number)
}) {
Image(countries[number]).renderingMode(.original)
.clipShape(Capsule())
.overlay(Capsule().stroke(Color.black, lineWidth: 1))
.shadow(color:.black, radius: 2)
}
}
Spacer()
}.alert(isPresented: $showingScore) {
Alert(title: Text(scoreTitle), message: Text("Your score is ??"), primaryButton: .cancel(Text("Cancel")){
},
secondaryButton: .destructive(Text(("Continue")))
{
askQuestion() }
)
}
}
}
func flagTapped(_ number: Int) {
print("number=\(number), correct=\(correctAnswer)")
if number == correctAnswer {
scoreTitle = "Correct"
} else {
scoreTitle = "Wrong"
}
showingScore = true
}
func askQuestion() {
countries.shuffled()
correctAnswer = Int.random(in: 0...2)
}
}
from:SwiftUI 100天 猜国旗