[英]Device screen width wrong when starting my Swift app in landscape
I use this code to get the screen width and height我使用此代码获取屏幕宽度和高度
public var width: CGFloat {
return UIScreen.main.bounds.width
}
public var height: CGFloat {
return UIScreen.main.bounds.height
}
After a rotation the code is working fine but if I start the app in Landscape mode, the returned height in viewDidLoad
is wrong and is 812.0, which is the width.旋转后代码工作正常,但如果我在横向模式下启动应用程序,
viewDidLoad
中返回的高度是错误的,是 812.0,即宽度。 If I rotate to portrait and than back to landscape, than the value is 375.0 which is right.如果我旋转到纵向而不是回到横向,则该值为 375.0,这是正确的。
According to this answer , you should run your code in viewWillAppear
and/or viewDidLayoutSubviews
.根据这个答案,您应该在
viewWillAppear
和/或viewDidLayoutSubviews
中运行您的代码。 When viewDidLoad
is called, that view controller's view is guaranteed to be loaded into memory, but it is not yet rendered.当
viewDidLoad
被调用时,该视图控制器的视图保证被加载到 memory 中,但它还没有被渲染。 viewWillAppear
is called when a view is about to be added to an on-screen view hierarchy, as detailed in the Apple developer documentation . viewWillAppear
在将要添加到屏幕视图层次结构中时调用 viewWillAppear,详见Apple 开发人员文档。 At this point, the view controller should be able to access the orientation that the device is in, since its content views will most likely be rendered when viewWillAppear
is called.此时,视图 controller 应该能够访问设备所在的方向,因为它的内容视图很可能会在调用
viewWillAppear
时呈现。 If your code is still returning the wrong values, you may need to move it into viewDidLayoutSubviews
, which is called whenever the bounds of the current view will change.如果您的代码仍然返回错误的值,您可能需要将其移动到
viewDidLayoutSubviews
中,只要当前视图的边界发生变化,就会调用它。
Edit: it looks like you will need to flip the width and height values based on the orientation and their relationship to one another, as stated in this answer , although that is in Objective-C.编辑:看起来您需要根据方向及其相互关系来翻转宽度和高度值,如本答案中所述,尽管这是在 Objective-C 中。 In Swift:
在 Swift 中:
public var width: CGFloat {
//If in landscape mode
if (UIApplication.shared.statusBarOrientation.isLandscape) {
//If in landscape and the width is less than the height (wrong),
//return the height instead of the width
if (UIScreen.main.bounds.width < UIScreen.main.bounds.height) {
return UIScreen.main.bounds.height
}
}
//Else just return the width
return UIScreen.main.bounds.width
}
public var height: CGFloat {
//If in landscape mode
if (UIApplication.shared.statusBarOrientation.isLandscape) {
//If in landscape and the height is greater than the width (wrong),
//return the width instead of the height
if (UIScreen.main.bounds.height > UIScreen.main.bounds.width) {
return UIScreen.main.bounds.width
}
}
//Else just return the height
return UIScreen.main.bounds.height
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.