【发布时间】:2021-12-05 10:32:52
【问题描述】:
我正在创建一个游戏,其中我有一个高分值,我想在每次更新时保存它,即使我退出应用程序也是如此。我已经有了 highscore 的值,它每次更新 score > highscore 但如果我退出应用程序,highscore 会重置为 0,我希望它保持不变。
导入 SwiftUI
struct Europe: View {
@State private var countries = ["Albania", "etc."].shuffled()
@State private var corrrectAnswer = Int.random(in: 0...5)
@State private var showingScore = false
@State private var scoreTitle = ""
@State private var userScore = 0
@State private var highScore = 0
var body: some View {
ZStack{
LinearGradient(gradient: Gradient(colors: [.white,.blue]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)
VStack(spacing:30){
VStack{
Text("Tap the flag of")
.foregroundColor(.black)
.fontWeight(.black)
Text(countries[corrrectAnswer])
.foregroundColor(.black)
.font(.largeTitle)
.fontWeight(.black)
}
VStack(spacing:50){
HStack(spacing:40) {
VStack(spacing:40) {
ForEach(0..<3){ number in
Button(action: {
self.flagTapped(number)
self.highScoreSet(number)
}){
Image(self.countries[number])
.resizable()
.frame(width: 130, height: 100)
.clipShape(Capsule())
.overlay(Capsule().stroke(Color.black,lineWidth: 1))
.shadow(color: .black, radius: 2)
}
}
}
VStack(spacing:40) {
ForEach(4..<7){ number in
Button(action: {
self.flagTapped(number)
self.highScoreSet(number)
}){
Image(self.countries[number])
.resizable()
.frame(width: 130, height: 100)
.clipShape(Capsule())
.overlay(Capsule().stroke(Color.black,lineWidth: 1))
.shadow(color: .black, radius: 2)
}
}
}
}
VStack{
Text("Score: \(userScore)")
.foregroundColor(.white)
.fontWeight(.black)
.font(.subheadline)
Text("High Score: \(highScore)")
.foregroundColor(.white)
.fontWeight(.black)
.font(.subheadline)
}
Spacer()
}
}
}
.alert(isPresented: $showingScore){
Alert(title: Text(scoreTitle), message: Text("Your score is \(userScore)"), dismissButton: .default(Text("Continue")){
self.askQuestion()})
}
}
func highScoreSet(_ number: Int){
if highScore < userScore {
highScore = userScore
}
}
func flagTapped(_ number: Int){
if number == corrrectAnswer{
scoreTitle = "Right"
userScore += 1
}
else {
scoreTitle = "Wrong!\n Thats the flag of \(countries[corrrectAnswer])"
userScore = 0
}
showingScore = true
}
func askQuestion(){
countries.shuffle()
corrrectAnswer = Int.random(in: 0...5)
}
}
struct Europe_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
【问题讨论】:
标签: swift swiftui swiftui-navigationview swiftui-form