Testing how to embed SpriteKit within a SwiftUI App.
The simple way is to use SpriteView as shown in Paul Hudson's tutorial.
However, that has two limitations:
- It requires a prebuilt Scene which will be resized to match later, which is counter to the way touchgram builds its scene.
- The
SpriteView
lacks any way for SpriteKit to change scenes other than via recreation.
The most obvious and one I didn't find a workaround for is that the transition parameter is completely ignored when you init a SpriteView with transition.
The subtle second bug occurs when you reuse the scene - after toggling a couple of times a blank gray view appears. Repeated tapping on the toggle button sometimes shows the correct image. This is regardless of specifying the transition so is unlikely to be the retention bug previously observed.
Both of these are regarded as intractable - will leave this as is to demonstrate this behaviour.
The escape hatch of UIViewRepresentable is used by SKViewApproach
.
Note some weird behaviour when this was the 2nd tab, it didn't appear to do the presentScene, unless the first tab had interacted. This may be the transition bug in action. I recommend strongly against mixing using SpriteView
in an app that also uses SKView
even if on different screens.
Using different tabs as shown here is a bit more problematic for cleanup - it shouldn't be a problem but note dismantleUIView is not invoked just changing tabs - it would only be when going to another screen or if the entire content is dropped from the view.
The sample was changed so in ContentView
now we can use the Hide SpriteKit Demos button to ensure destruction happens.
if isShowingSpriteKit {
TabView {
SKViewApproach...
Going to the SpriteKit view and back out again with Hide SpriteKit Demos will show the following in the debug console in Xcode.
InitLogger init - SKContainer
dismantleView invoked in SKViewApproach
InitLogger deinit - SKContainer