First need a Bool
to track which View is showning
@State private var isGameStarted = false
Then in the ContentView you can have, which will show either view depend on isGameStarted
var body: some View {
if isGameStarted {
GameView()
} else {
SettingsView()
}
}
now need to be able to change between so add a method
func startGame() {
isGameStarted = true
}
but what needed is say number of questions to answer as a Int
@State private var numberQuestions = 0
need to be able set numberQuestions
so change the method
func startGame(with numberQuestions: Int) {
self.numberQuestions = numberQuestions
isGameStarted = true
}
and now can pass the numberQuestions
to the GameView
var body: some View {
if isGameStarted {
GameView(numberQuestions: numberQuestions)
} else {
SettingsView()
}
}
so now we need to be able to call the startGame
method this method take an Int and return nothing which (Int) -> Void
so in the SettingView
we need to add let startGame: (Int) -> Void
and then you can do a Button with action to start the game
struct SettingsView: View {
@State private var numberQuestions = 0
let startGame: (Int) -> Void
var body: some View {
VStack {
HStack {
Text("Number of Questions")
Picker("Number of Questions", selection: $numberQuestions) {
ForEach(1..<50) {
Text("\($0)")
}
}
}
Button("Start Game") {
startGame(numberQuestions + 1)
}
.buttonStyle(.borderedProminent)
}
}
}
This is very rough as just want to show how to pass the method from one view to another (took me age to get this). It might give you a starting point for the challange.
struct ContentView: View {
@State private var isGameStarted = false
@State private var numberQuestions = 0
var body: some View {
if isGameStarted {
GameView(numberQuestions: numberQuestions)
} else {
SettingsView(startGame: startGame)
}
}
func startGame(with numberQuestions: Int) {
self.numberQuestions = numberQuestions
isGameStarted = true
}
}
struct GameView: View {
let numberQuestions: Int
var body: some View {
Text("Game playing \(numberQuestions) questions")
}
}
struct SettingsView: View {
@State private var numberQuestions = 0
let startGame: (Int) -> Void
var body: some View {
VStack {
HStack {
Text("Number of Questions")
Picker("Number of Questions", selection: $numberQuestions) {
ForEach(1..<50) {
Text("\($0)")
}
}
}
Button("Start Game") {
startGame(numberQuestions + 1)
}
.buttonStyle(.borderedProminent)
}
}
}