[英]Set a value to default which constantly changes
I am creating a game where I have a value of highscore which I want to save each time it is updated even if I exit the app.我正在创建一个游戏,其中我有一个高分值,即使我退出应用程序,我也想在每次更新时保存它。 I have already the value of highscore which updates eveyrtime the score > highscore but if I exit the app, it the highscore resets to 0 and I want it to maintain.我已经有了 highscore 的值,它会更新每个时间的 score > highscore 但如果我退出应用程序,highscore 会重置为 0,我希望它保持不变。
import SwiftUI导入 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()
}
}
You can use the @AppStorage
property wrapper.您可以使用@AppStorage
属性包装器。 Good article here on how to use it.好文章在这里就如何使用它。
Change:改变:
@State private var highScore = 0
To:到:
@AppStorage("high_score") private var highScore = 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.