Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/102.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在横向中启动我的Swift应用程序时设备屏幕宽度错误_Ios_Swift_Landscape - Fatal编程技术网

Ios 在横向中启动我的Swift应用程序时设备屏幕宽度错误

Ios 在横向中启动我的Swift应用程序时设备屏幕宽度错误,ios,swift,landscape,Ios,Swift,Landscape,我使用这个代码来获得屏幕的宽度和高度 public var width: CGFloat { return UIScreen.main.bounds.width } public var height: CGFloat { return UIScreen.main.bounds.height } 旋转后,代码工作正常,但如果我以横向模式启动应用程序,则viewDidLoad中返回的高度错误,为812.0,即宽度。如果我旋转到纵向,然后再旋转回横向,则值为375.0,这是正确的

我使用这个代码来获得屏幕的宽度和高度

public var width: CGFloat {
    return UIScreen.main.bounds.width
}

public var height: CGFloat {
    return UIScreen.main.bounds.height
}
旋转后,代码工作正常,但如果我以横向模式启动应用程序,则
viewDidLoad
中返回的高度错误,为812.0,即宽度。如果我旋转到纵向,然后再旋转回横向,则值为375.0,这是正确的。

根据,您应该在
视图中将出现
和/或
视图布局子视图中运行代码。调用
viewDidLoad
时,该视图控制器的视图保证加载到内存中,但尚未呈现<代码>视图将出现
在视图即将添加到屏幕视图层次结构时调用,如中所述。此时,视图控制器应该能够访问设备所在的方向,因为当调用
viewwillbeen
时,其内容视图很可能会呈现。如果代码仍然返回错误的值,则可能需要将其移动到
viewdilayoutsubviews
,只要当前视图的边界发生更改,就会调用该视图

编辑:看起来您需要根据方向及其相互之间的关系翻转宽度和高度值,如中所述,尽管这在Objective-C中。在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
}
公共变量宽度:CGFloat{
//如果处于横向模式
if(UIApplication.shared.statusBarOrientation.isLandscape){
//如果在景观中,宽度小于高度(错误),
//返回高度而不是宽度
if(UIScreen.main.bounds.widthUIScreen.main.bounds.width){
返回UIScreen.main.bounds.width
}
}
//否则就返回高度
返回UIScreen.main.bounds.height
}

我尝试了ViewWillDisplay和ViewDidLayoutSubView,但仍然存在相同的问题。我必须将设备旋转到纵向,然后再旋转到横向,以获得正确的高度值谢谢。我想实现一些类似的东西,但我想了解是什么导致了问题,以及是否有更干净的方法来解决that@mbbf我真的不确定是什么导致了这一切。根据UIScreen.main.bounds的文档,(),“此矩形在当前坐标空间中指定,该坐标空间考虑了设备的任何有效接口旋转。”这是在模拟器中发生的,还是在物理iOS设备上发生的,还是两者都发生的?未在模拟器中尝试过,仅在物理iOS上尝试device@mbbf模拟器倾向于带有面向设备的东西,但是如果它不能在真正的iOS设备上工作,那么肯定有一个bug。根据这个答案(),这似乎与iOS如何处理在横向环境中启动应用程序有关。这些变通办法表明那里与我的非常相似。