我有一个带1个按钮的屏幕,按下该按钮可以创建一个新游戏。它应该创建一个随机的type
游戏,该游戏将确定每次我按New Game
时要使用的颜色。问题在于,一旦加载视图,一次单击后就不会更新以选择随机的新主题。我尝试创建一个@State var theme
并使用onAppear
重新渲染视图,但这似乎是一种hack ...
有没有一种方法可以正确地动态加载导航链接?
struct NewGameView: View {
@State var theme: EmojiMemoryGameTheme
var body: some View {
NavigationView {
NavigationLink(destination: EmojiMemoryGameView(viewModel: EmojiMemoryGame(theme: theme))) {
VStack {
Text("New Game")
.font(Font.largeTitle)
.padding(.vertical, 10.0)
.padding(.horizontal, 40.0)
.background(Color.blue)
.cornerRadius(20.0)
.foregroundColor(Color.white)
}
}
.navigationBarTitle("Memorize")
.onAppear {
self.newTheme()
}
}
}
func newTheme() {
theme = EmojiMemoryGameTheme.allCases.randomElement() ?? .halloween
}
}
答案 0 :(得分:0)
检查一下:
请尝试提供一个可重复的示例,如下次https://stackoverflow.com/help/minimal-reproducible-example所述;)
import SwiftUI
enum EmojiMemoryGameTheme : String, CaseIterable {
case you
case should
case provide
case a
case reproducable
case example
}
struct EmojiMemoryGame {
var theme:EmojiMemoryGameTheme
}
struct EmojiMemoryGameView : View {
var viewModel : EmojiMemoryGame
var body: some View {
Group {
Text(viewModel.theme.rawValue)
}
}
}
struct ContentView: View {
@State var theme: EmojiMemoryGameTheme
var body: some View {
NavigationView {
NavigationLink(destination: EmojiMemoryGameView(viewModel: EmojiMemoryGame(theme:theme))) {
VStack {
Text("New Game")
.font(Font.largeTitle)
.padding(.vertical, 10.0)
.padding(.horizontal, 40.0)
.background(Color.blue)
.cornerRadius(20.0)
.foregroundColor(Color.white)
.onAppear() {
self.theme = EmojiMemoryGameTheme.allCases.randomElement() ?? .a
}
}
.navigationBarTitle("Memorize")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(theme: EmojiMemoryGameTheme.example)
}
}