iosswiftuispriteview

How to rotate a SpriteView?


UPDATE: The SpriteView rotation will work in a simulator, but not on a real device (in my case an iPhone 11 with iOS 14b3). See @Asperi comment. ¯_(ツ)_/¯

SpriteView: A SwiftUI view that renders a SpriteKit scene.
Ok.

First, the happy path. The Rectangle below will rotate just fine:

import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in

            // Rectangle test (rotates just fine)
            Rectangle()
                .fill(Color.red)
                .frame(width: geometry.size.width / 2, height: geometry.size.height / 2)
        }
    }
}

As expected:

rotationRectangle

Great.
Now when I try to do the same with a SpriteView:

import SwiftUI
import SpriteKit

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            SpriteView(scene: createSKScene(with: geometry.size))
                .frame(width: geometry.size.width / 2, height: geometry.size.height / 2)
        }
    }

    func createSKScene(with size: CGSize) -> SKScene {
        let scene = SKScene()
        scene.backgroundColor = UIColor.blue
        scene.scaleMode = .resizeFill
        return scene
    }
}

The view will not rotate.

spriteView

So clearly I'm missing something. Do you know what I'm missing?


Now one thing that is very curious...
By just adding this line: let scene = SKScene()

... views will simply stop rotating.

import SwiftUI
import SpriteKit

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {

    // By adding this line, views won't rotate anymore. ???
    let scene = SKScene()

    var body: some View {
        GeometryReader { geometry in

            // Now the rectangle will NOT rotate anymore.
            Rectangle()
                .fill(Color.red)
                .frame(width: geometry.size.width / 2, height: geometry.size.height / 2)
        }
    }
}

This is driving me nuts! 😁

Xcode: 12.0 beta 3
iOS: 14 beta 3


Solution

  • Fixed in Xcode 12 beta 6.

    ¯\_(ツ)_/¯