如何解决更改方向后,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)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。