从 SpriteKit 场景移动到 SwiftUI 视图
Posted
技术标签:
【中文标题】从 SpriteKit 场景移动到 SwiftUI 视图【英文标题】:Move From SpriteKit scene to SwiftUI View 【发布时间】:2022-01-20 20:09:10 【问题描述】:我正在尝试找出从 SpriteKit 场景移回 SwiftUI 视图的正确方法。我目前有一个 Swift UI “主菜单”,看起来像这样。
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)
ContentView() 是包含 SpriteKit 游戏的内容,如下所示。
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()
我的问题是……进入 ContentView 后如何返回“主菜单”?
感谢您提供的任何帮助。
【问题讨论】:
【参考方案1】:你可以使用
@Environment(.presentationMode) varpresentationMode
这样你就可以创建一个按钮并调用
presentationMode.wrappedValue.dismiss()
或者您可以将绑定变量传递给内容视图并设置为 false,如下所示:
在主菜单中
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)
在内容视图中:
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")
【讨论】:
感谢您的帮助,它让我再次朝着正确的方向前进。 :)以上是关于从 SpriteKit 场景移动到 SwiftUI 视图的主要内容,如果未能解决你的问题,请参考以下文章
SpriteKit:场景中的静态背景与移动的 SKCameraNode
SwiftUI 按钮点击重置 SpriteKit 动画 - 这是一个错误吗?
带有 SpriteView 和 SwiftUI 的场景不会填满整个屏幕