ios - 更改方向时,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 ,但我无法让它正常运行。
解决方案
请尝试以下方法
var body: some View {
GeometryReader { gp in
SpriteView(scene: scene)
.frame(width: gp.size.width, height: gp.size.height)
}
.edgesIgnoringSafeArea(.all)
}
推荐阅读
- python-3.x - Python 多处理管理器和代理;为什么我的自定义类不通过网络共享?
- html - 如何绕过 CSS Font-Variant-Ligatures?
- python - 使用tweepy转推时如何排除关键字或将某些关键字列入黑名单
- python-3.x - 在文件中最后一次出现后删除所有文本
- javascript - 在控制器nestjs中注入一个简单的类
- c - 如何获取 C99 中的时区?
- laravel - 如何为 Laravel Restful Api 生成 api 密钥
- android - 使用 Flow 时 Android 房间查询为空
- javascript - 第一次 React-native:错误:代码:400,详细信息:对象,消息:请求 [0].image.source 处的值无效
- python - 如何在python中绘制实际值与预测值的图表?