I'm trying to figure out the proper way to move back to a SwiftUI view from a SpriteKit Scene. I currently have a Swift UI "main menu" which looks like this.
struct MainMenu: View {
var body: some View {
NavigationView {
VStack {
Text("Replicator")
.font(.largeTitle)
.fontWeight(.bold)
.padding()
NavigationLink(destination: ContentView().navigationBarBackButtonHidden(true)) {
HStack {
Image(systemName: "play.circle")
.font(.title3)
Text("Start")
.font(.title)
}
.frame(width: 250, height: 50)
.background(.cyan)
.cornerRadius(25)
.foregroundColor(.white)
}
}
}
}
}
The ContentView() is what contains the SpriteKit game and that looks like the following.
struct ContentView: View {
var scene: SKScene {
let scene = Level_1()
scene.size = CGSize(width: 750, height: 1334)
scene.scaleMode = .aspectFit
return scene
}
var body: some View {
VStack {
SpriteView(scene: scene)
.ignoresSafeArea()
}
}
}
My question is... once I'm in ContentView how do I return to "Main Menu"?
Thanks for any help you can provide.
CodePudding user response:
You can use
@Environment(.presentationMode) var presentationMode
So you can create a button and call
presentationMode.wrappedValue.dismiss()
Or you can pass a binding var to Content View and set to false like so:
In MainMenu
struct MainMenu: View {
@State var isPresented = false
var body: some View {
NavigationView {
VStack {
Text("Replicator")
.font(.largeTitle)
.fontWeight(.bold)
.padding()
NavigationLink(destination: ContentView(isPresented: $isPresented).navigationBarBackButtonHidden(true), isActive: $isPresented) {
HStack {
Image(systemName: "play.circle")
.font(.title3)
Text("Start")
.font(.title)
}
.frame(width: 250, height: 50)
.background(.cyan)
.cornerRadius(25)
.foregroundColor(.white)
}
}
}
}
}
In ContentView:
struct ContentView: View {
@Binding var isPresented: Bool
var scene: SKScene {
let scene = Level_1()
scene.size = CGSize(width: 750, height: 1334)
scene.scaleMode = .aspectFit
return scene
}
var body: some View {
ZStack {
SpriteView(scene: scene)
.ignoresSafeArea()
Button(action: { //You can put the button wherever you want as long as you pass in the isPresented Binding
isPresented.toggle()
}) {
Text("Back to MainMenu")
}
}
}
}