更改方向后,SwiftUI中的SKScene无法填充屏幕

问题描述

我有一个SKScene,我正在SwiftUI中使用以下代码进行演示:

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)
        
    }
}

我希望能够更改设备的方向以在横向和纵向模式下均可使用。在我的GameScene类中,我在Initialiser语句内添加以下方法

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

,然后在GameScene类中添加以下功能

 @objc func orientationChanged(notification : NSNotification) {
    }

我可以为此添加打印语句,并且可以确认每次更改方向时都正确调用了该语句。我的问题是视图旋转,但是无法正确更新。我尝试添加

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

如果我观察到打印行,则可以确定GameScene的大小正在更新,但是在设备上无法正确显示。实际上,我的人像视图似乎只是在旋转,因此宽度是屏幕的中央一半,而在横向模式下,高度超出了设备的边缘。

我尝试在SwiftUI代码中更改.aspectFill,但是我无法使其正常运行。

解决方法

尝试以下方法

var body: some View {
   
    GeometryReader { gp in
      SpriteView(scene: scene)
        .frame(width: gp.size.width,height: gp.size.height)
    }
    .edgesIgnoringSafeArea(.all)
}