Switching views in Swift UI

Hi all,

First post here

I’m new to swift and decided to learn SwiftUI. I have previous programming experience though. I was wondering if there was a way of switching between views without using the navigationlink and navigation bar displayed.
Example:
Homescreen view - setting, etc
Maingameview - where the game is played.

Home Screen of a game with a play button. When the button is pressed you switch the the maingameview where the game is played.

The only way I seem to be able to achieve this is using the navigation view and navigation link but then I get the nav bar and I’m also unable to overlay this link on top of a background image.

I hope that makes sense.

Thank you
Answered by BabyJ in 649161022
You can use a simple variable to control which view shows when
Code Block Swift
@State private var showingGame = false
var body: some View {
if showingGame {
MainGameView()
} else {
HomeScreenView()
}
}

and add a button that toggles showingGame.
Accepted Answer
You can use a simple variable to control which view shows when
Code Block Swift
@State private var showingGame = false
var body: some View {
if showingGame {
MainGameView()
} else {
HomeScreenView()
}
}

and add a button that toggles showingGame.
Hi,

I tried this this morning. In a basic new document.

when I use a button to toggle the GameView the gameview shows but the button is still showing in my new view? I added text to the views to see what was showing and the text changes but can’t shift this button.

thanks
In order to change the entire view, here is a solution: https://stackoverflow.com/a/56798708/2306349

Return a Group in the base view like this:

Code Block swift
@State private var showingGame = falsevar
body: some View {
return Group {
if showingGame {
MainGameView()
} else {
HomeScreenView()
}
}
}


Switching views in Swift UI
 
 
Q