首页 > 解决方案 > 更改方向时,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 类中,我在初始化语句中添加了以下方法:

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 ,但我无法让它正常运行。

标签: iosswiftsprite-kitswiftuiorientation

解决方案


请尝试以下方法

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

推荐阅读