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/45203139/

相关文章:

ios - dequeueReusableCellWithIdentifier 不返回单元格

ios - Unity VR LandscapeLeft 在 iOS 中不起作用

iphone - 方向不适用于 AlertView 内的 UITableview

objective-c - 如何在 UIScrollView 内的 UIWebView 上启用放大功能?

ios - 在多个 View Controller 中使用相同的变量

ios - NSURL 到带有 XCTest 的测试包中的文件路径

camera - 获取由具有已知位置和方向的相机查看的对象的 3D 位置

ios - 导出到 Assets 后崩溃并发出警告 "connection to assetsd was interrupted or assetsd died"

swift - 访问父属性

ios - 无法在 Swift 中观察 UIPageControl 的 currentPage 变化