尝试获取应用程序方向时,iOS 13.0 中不推荐使用“statusBarOrientation”

Cod*_*der 30 ios swift ios13

简单地说,我依靠以下代码来提供应用程序的方向。在应用程序中使用它有几个原因:

  • 根据 UX 规范,stackview 的布局是根据 iPad 的方向设置的(横向时为水平,纵向时为垂直)
  • 在上一项的基础上,stackview 被放置在屏幕的左侧(纵向)或顶部(横向)
  • 有自定义轮换逻辑,根据状态做出不同的响应。tl;dr 是在 iPad 上,该应用程序在方向之间呈现出显着差异

在这种情况下,我只是负责维护,并且无法做出偏离当前(并且正常运行)布局逻辑的重大更改。

截至目前,它依赖于以下内容来捕获应用程序方向:

var isLandscape: Bool {
    return UIApplication.shared.statusBarOrientation.isLandscape
}
Run Code Online (Sandbox Code Playgroud)

但是,对于 Xcode 11 GM 版本,我收到了以下弃用警告:

'statusBarOrientation' 在 iOS 13.0 中被弃用:改用窗口场景的 interfaceOrientation 属性。

如何通过状态栏获取应用程序的方向?

小智 22

Swift 5 , iPadOS 13,考虑到多窗口环境

if let interfaceOrientation = UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.windowScene?.interfaceOrientation {
 // Use interfaceOrientation
}
Run Code Online (Sandbox Code Playgroud)


Sas*_*sho 22

Swift 5 , iOS 13,但与旧版本的 iOS兼容

extension UIWindow {
    static var isLandscape: Bool {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.windows
                .first?
                .windowScene?
                .interfaceOrientation
                .isLandscape ?? false
        } else {
            return UIApplication.shared.statusBarOrientation.isLandscape
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

if (UIWindow.isLandscape) {
    print("Landscape")
} else {
    print("Portrait")
}
Run Code Online (Sandbox Code Playgroud)


Geo*_*f H 15

这就是我为Swift 5.1 的iOS13 所做的:

var statusBarOrientation: UIInterfaceOrientation? {
    get {
        guard let orientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation else {
            #if DEBUG
            fatalError("Could not obtain UIInterfaceOrientation from a valid windowScene")
            #else
            return nil
            #endif
        }
        return orientation
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于使用调试版本进行测试,您不需要测试调试并使用 fatalError,因为断言旨在实现您在此处所需的行为。断言只能在调试中工作并获得相同的结果(带有可选错误消息的崩溃)。https://developer.apple.com/documentation/swift/1541112-assert (6认同)

Cod*_*der 8

我想出了以下解决方案,但如果我犯了一些我不知道的错误,我愿意接受改进或建议:

var isLandscape: Bool {
    return UIApplication.shared.windows
        .first?
        .windowScene?
        .interfaceOrientation
        .isLandscape ?? false
}
Run Code Online (Sandbox Code Playgroud)


ban*_*na1 6

Objective C、iOS 13 和旧版本兼容:

+ (BOOL)isLandscape
{
    if (@available(iOS 13.0, *)) {
        UIWindow *firstWindow = [[[UIApplication sharedApplication] windows] firstObject];
        if (firstWindow == nil) { return NO; }

        UIWindowScene *windowScene = firstWindow.windowScene;
        if (windowScene == nil){ return NO; }

        return UIInterfaceOrientationIsLandscape(windowScene.interfaceOrientation);
    } else {
        return (UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication.statusBarOrientation));
    }
}
Run Code Online (Sandbox Code Playgroud)

我将此添加到一个UIWindow类别中。