swift - 数组没有被洗牌并且屏幕被重绘
问题描述
正如你所看到的,我有一个函数应该对我的国家数组进行洗牌,因为@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@*/)
}
}
}
}
}
}
解决方案
这是一个修复
func askQuestion() {
countries = countries.shuffled() // << assign !!
correctAnswer = Int.random(in: 0...2)
}
推荐阅读
- php - PhP日期时间添加
- javascript - less.js 在 Chrome 扩展上获得同步 XMLHttpRequest 错误
- mongodb - Mongo查询 - 获取与过滤器列表中的指定值不完全匹配的记录
- node.js - 生产模式下的 Electron 应用程序无法在 Mac 中通过 child_process.spawnSync API 运行外部脚本,但在 Linux 中运行良好
- c# - 基于已解析属性的 HotChocolate 过滤器集合
- vue.js - Vuex mapState 基于路由和路由参数
- python - sqlAlchemy:无法确定父/子表之间的连接条件
- c - 创建一个使用不同数据类型的数组的静态结构
- java - 从扩展名确定文件类型
- android - 查看 longclick 被 textView 子级中止