简单地说,我依靠以下代码来提供应用程序的方向。在应用程序中使用它有几个原因:
在这种情况下,我只是负责维护,并且无法做出偏离当前(并且正常运行)布局逻辑的重大更改。
截至目前,它依赖于以下内容来捕获应用程序方向:
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)
我想出了以下解决方案,但如果我犯了一些我不知道的错误,我愿意接受改进或建议:
var isLandscape: Bool {
return UIApplication.shared.windows
.first?
.windowScene?
.interfaceOrientation
.isLandscape ?? false
}
Run Code Online (Sandbox Code Playgroud)
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
类别中。
归档时间: |
|
查看次数: |
18222 次 |
最近记录: |