0

I have a screen with 1 button that creates a new game when pressed. It should create a random type of game that will determine the colors being used everytime I press New Game. The issue is that once the view is loaded it never updates to select a random new theme after pressing it once. I have tried create a @State var theme and used onAppear to rerender the view but this seems like a hack...

Is there a way to properly load navigation links dynamically?

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
    }
}
Jeremy Sh
  • 609
  • 7
  • 24

1 Answers1

0

check this out:

please try to provide a reproducible example as explained here https://stackoverflow.com/help/minimal-reproducible-example next time ;)

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)
    }
}
Chris
  • 7,579
  • 3
  • 18
  • 38