Using SpriteKit inside SwiftUI

后端 未结 5 1415
说谎
说谎 2020-12-15 07:52

I am having an issue when creating a SpriteKit scene within SwiftUI. I created this project initially as a SwiftUI project.

Her

5条回答
  •  独厮守ぢ
    2020-12-15 08:18

    You SceneView implementation is incorrect.

    SwiftUI uses structs to builds views in its DSL - not views.

    You want to create a struct that conforms to UIViewRepresentable.

    struct SceneView: UIViewRepresentable {
    
        let scene: SKScene
    
        func makeUIView(context: Context) -> SKView {
            // Let SwiftUI handle the sizing
            return SKView(frame: .zero)
        }
    
        func updateUIView(_ uiView: SKView, context: Context) {
            uiView.presentScene(scene)
        }
    }
    

    For more info on how to port UIKit-based views to SwiftUI, see this excellent WWDC 2019 video: Integrating SwiftUI.

提交回复
热议问题