ios - 在 Swift 中获取设备方向

标签 ios swift orientation

我想知道如何在 Swift 中获取当前设备方向?我知道有针对 Objective-C 的示例,但我无法让它在 Swift 中运行。

我正在尝试获取设备方向并将其放入 if 语句中。

这是我遇到最多问题的行:

[[UIApplication sharedApplication] statusBarOrientation]

最佳答案

你可以使用:

override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
    var text=""
    switch UIDevice.currentDevice().orientation{
    case .Portrait:
        text="Portrait"
    case .PortraitUpsideDown:
        text="PortraitUpsideDown"
    case .LandscapeLeft:
        text="LandscapeLeft"
    case .LandscapeRight:
        text="LandscapeRight"
    default:
        text="Another"
    }
    NSLog("You have moved: \(text)")        
}

SWIFT 3 更新

override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
    var text=""
    switch UIDevice.current.orientation{
    case .portrait:
        text="Portrait"
    case .portraitUpsideDown:
        text="PortraitUpsideDown"
    case .landscapeLeft:
        text="LandscapeLeft"
    case .landscapeRight:
        text="LandscapeRight"
    default:
        text="Another"
    }
    NSLog("You have moved: \(text)")        
}

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
}

通过通知您可以查看:IOS8 Swift: How to detect orientation change?

NOTE : didRotateFromInterfaceOrientation is Deprecated Use viewWillTransitionToSize for iOS 2.0 and later

在面朝上和面朝下的情况下,这将不起作用。 所以我们需要使用以下内容。

if UIApplication.shared.statusBarOrientation.isLandscape {
     // activate landscape changes
} else {
     // activate portrait changes
}

关于ios - 在 Swift 中获取设备方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25796545/

相关文章:

iOS:dyld:未加载库:@rpath/CocoaLumberjack.framework/CocoaLumberjack

ios - 为什么 AppDelegate.swift 窗口是可选的?

objective-c - 使用 Swift 访问类单例时的 semaphore_wait_trap

ios - 在其自身的功能中无法推送 View Controller

android - 在一致的方向更改后重新创建完成的 Activity

objective-c - 从 UITextField 单击事件 MonoTouch 在 UIDatePicker 中选择日期

ios - 如何确定 UITextField 内文本的大小(包括光标)?

ios - 在 xcode 10 中找不到体系结构 x86_64 的符号

php - 使用 Ghostscript 时禁止旋转 PDF 中的页面

android - FragmentActivity 与 ViewPager : Crash on orientation change