我想知道如何在 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/