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

查看:40
本文介绍了在 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.

这是我目前的代码:

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:

Scene 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?

推荐答案

SwiftUI 2

现在有一个负责显示 SKScene 的原生视图 - 它被称为 SpriteView.

SwiftUI 2

There is now a native view responsible for displaying a SKScene - it's called SpriteView.

假设我们有一个简单的SKScene:

Assuming we have a simple SKScene:

class Scene: SKScene {
    override func didMove(to view: SKView) {
        ...
    }
}

我们可以使用 SpriteView 直接在 SwiftUI 视图中显示它:

we can use a SpriteView to display it directly in a SwiftUI view:

struct ContentView: View {
    var scene: SKScene {
        let scene = Scene()
        scene.size = CGSize(width: 300, height: 400)
        scene.scaleMode = .fill
        return scene
    }

    var body: some View {
        SpriteView(scene: scene)
            .frame(width: 300, height: 400)
            .edgesIgnoringSafeArea(.all)
    }
}


您可以在此处找到更多信息:


You can find more information here:

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

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