Communication between SpriteView and normal View

457 Views Asked by At

I am currently working on a project, where I use SpriteView to display game content and normal Views to display menus and navigation in general. I am able to create and load SpriteViews when pressing buttons in the normal view but the communication does not work the other way. I want to be able to change State variables in the parent View-Element by using buttons/SKShapeNodes of the child SpriteView-Element.

I tried Binding variables between the two instances and using callback-functions. But I wasn't able to change any content in the View-Element.

Is there a simple and effective way to send requests from a child-SpriteView to the parent-View ?

1

There are 1 best solutions below

0
clns On

You can use the ObservableObject - @Published pattern for this.

Make your GameScene conform to the ObservableObject protocol and publish the properties that you are interested to send the values of into the SwiftUI views, something like this:

class GameScene: SKScene, ObservableObject {
    @Published var updates = 0
    @Published var isPressed = false
    // ...
}

Then, in your SwiftUI view, use a @StateObject property (or an @ObservedObject or an @EnvironmentObject) to store the GameScene instance. You can then use the GameScene's published properties in your SwiftUI view:

struct ContentView: View {
    @StateObject private var scene: GameScene = {
        let scene = GameScene()
        scene.size = CGSize(width: 300, height: 400)
        return scene
    }()
    
    var body: some View {
        ZStack {
            SpriteView(scene: scene).ignoresSafeArea()
            VStack {
                Text("Updates from SKScene: \(scene.updates)")
                if scene.isPressed {
                    Text("isPressed is true inside GameScene")
                }
            }
        }
    }
}

When you "press buttons in the normal view", change the value of the published properties, and they will change the SwiftUI views that uses them.