【发布时间】:2019-10-30 02:17:21
【问题描述】:
在SwiftUI 中创建SpriteKit 场景时遇到问题。我最初将这个项目创建为 SwiftUI 项目。
这是我目前的代码:
ContentView.swift:
/// Where the UI content from SwiftUI originates from.
struct ContentView : View {
var body: some View {
// Scene
SceneView().edgesIgnoringSafeArea(.all)
}
}
SceneView.swift:
/// Creates an SKView to contain the GameScene. This conforms to UIViewRepresentable, and so can be used within SwiftUI.
final class SceneView : SKView, UIViewRepresentable {
// Conformance to UIViewRepresentable
func makeUIView(context: Context) -> SKView {
print("Make UIView")
return SceneView(frame: UIScreen.main.bounds)
}
func updateUIView(_ uiView: SKView, context: Context) {
print("Update UIView")
}
// Creating scene
override init(frame: CGRect) {
super.init(frame: frame)
let scene = Scene(size: UIScreen.main.bounds.size)
presentScene(scene)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Scene.swift:
/// The scene for the game in SpriteKit.
final class Scene : SKScene {
override func didMove(to view: SKView) {
super.didMove(to: view)
print("Scene didMove:")
}
}
问题
问题是场景多次重载,如日志所示(因为代码中有prints):
场景确实移动:
制作 UIView
场景确实移动:
更新 UIView
如您所见,Scene didMove: 被打印了两次。我只希望调用一次,因为我想在这里创建我的精灵。有什么想法吗?
【问题讨论】:
-
不要在初始化中展示你的场景
标签: ios swift sprite-kit skscene swiftui