SKScene in SwiftUI is not filling screen when orientation is changed

I have an SKScene which I am presenting in SwiftUI with the code below:

struct ContentView: View{   var scene: SKScene {     let scene = GameScene(size: CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))          scene.scaleMode = .aspectFill     return scene }  var body: some View {                       SpriteView(scene: scene)         .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)         .edgesIgnoringSafeArea(.all)              } } 

I would like to be able to change the orientation of my device to work in landscape as well as portrait. In my GameScene class I add the following method within the initialiser statement:

UIDevice.current.beginGeneratingDeviceOrientationNotifications()     //add the observer     NotificationCenter.default.addObserver(         self,         selector: #selector(orientationChanged(notification:)),         name: UIDevice.orientationDidChangeNotification,         object: nil) 

and then add the following function within the GameScene class:

 @objc func orientationChanged(notification : NSNotification) {     } 

I can add a print statement to this and can confirm that this is correctly called every time the orientation is changed. My issue is that the view rotates, however does not properly update. I have tried adding:

let screenSize = CGSize(width: UIScreen.main.bounds.height, height: UIScreen.main.bounds.width) self.size = screen size print(self.size) 

If I observe my print line, I can determine that the size of my GameScene is being updated, however this is not displaying correctly on the device. In reality it looks like my portrait view is just being rotated, and so the width is the central half of the screen, and the height goes off the edges of the device when in landscape mode.

I have tried changing .aspectFill in the SwiftUI code, but I cannot get this to behave correctly.

Add Comment
1 Answer(s)

Try instead the following

var body: some View {         GeometryReader { gp in       SpriteView(scene: scene)         .frame(width: gp.size.width, height: gp.size.height)     }     .edgesIgnoringSafeArea(.all) } 
Answered on September 1, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.