在SwiftUI中使用SpriteKit [英] Using SpriteKit inside SwiftUI

查看:286
本文介绍了在SwiftUI中使用SpriteKit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SwiftUI中创建SpriteKit场景时遇到问题.我最初将此项目创建为SwiftUI项目.

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

这是我到目前为止的代码:

Here is the code I have so far:

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:")
    }
}


问题

问题是场景正在重新加载多次,如日志所示(因为代码中有print):

场景didMove:

Scene didMove:

制作UIView

场景didMove:

更新UIView


如您所见,Scene didMove:被打印两次.我只想调用一次,因为我想在这里创建我的精灵.有什么想法吗?


As you can see, Scene didMove: is printed twice. I only want this to be called once, as I want to create my sprites here. Any ideas?

推荐答案

您的SceneView实现不正确.

SwiftUI使用结构在其DSL中构建视图-而不是视图.

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

您要创建一个符合UIViewRepresentablestruct.

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)
    }
}

有关如何将基于UIKit的视图移植到SwiftUI的更多信息,请参见以下出色的WWDC 2019视频:集成SwiftUI .

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

这篇关于在SwiftUI中使用SpriteKit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆