ios 在 Swift 中获取设备方向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25796545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting device orientation in Swift
提问by user3746428
I was wondering how I can get the current device orientation in Swift? I know there are examples for Objective-C, however I haven't been able to get it working in Swift.
我想知道如何在 Swift 中获取当前设备方向?我知道有 Objective-C 的示例,但是我无法在 Swift 中使用它。
I am trying to get the device orientation and put that into an if statement.
我正在尝试获取设备方向并将其放入 if 语句中。
This is the line that I am having the most issues with:
这是我遇到最多问题的线路:
[[UIApplication sharedApplication] statusBarOrientation]
回答by Miguel
you can use:
您可以使用:
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 UPDATE
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)")
}
or
或者
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
}
with Notification you can check: IOS8 Swift: How to detect orientation change?
使用通知,您可以检查:IOS8 Swift:如何检测方向变化?
NOTE :didRotateFromInterfaceOrientationis Deprecated Use viewWillTransitionToSizefor iOS 2.0 and later
注意:不推荐使用didRotateFromInterfaceOrientation对 iOS 2.0 及更高版本使用 viewWillTransitionToSize
In case of Face up and Face Down this will not work. So we need to use the following.
在面朝上和面朝下的情况下,这将不起作用。所以我们需要使用以下内容。
if UIApplication.shared.statusBarOrientation.isLandscape {
// activate landscape changes
} else {
// activate portrait changes
}
回答by Mike S
To get the status bar (and therefor UI) orientation like the Objective-C code you have, it's simply:
要像您拥有的 Objective-C 代码一样获得状态栏(以及因此的 UI)方向,只需:
UIApplication.sharedApplication().statusBarOrientation
You can also use the orientation
propertyof UIDevice:
您还可以使用UIDevice的orientation
属性:
UIDevice.currentDevice().orientation
However, that may not match what orientation your UI is in. From the docs:
但是,这可能与您的 UI 所在的方向不匹配。来自文档:
The value of the property is a constant that indicates the current orientation of the device. This value represents the physical orientation of the device and may be different from the current orientation of your application's user interface. See “UIDeviceOrientation” for descriptions of the possible values.
该属性的值是一个常数,表示设备的当前方向。此值表示设备的物理方向,可能与应用程序用户界面的当前方向不同。有关可能值的说明,请参阅“UIDeviceOrientation”。
回答by zSprawl
Apple recently got rid of the idea of Landscape vs. Portrait and prefers we use screen size. However, this works:
苹果最近摆脱了横向与纵向的想法,更喜欢我们使用屏幕尺寸。但是,这有效:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.currentDevice().orientation.isLandscape.boolValue {
print("landscape")
} else {
print("portrait")
}
}
回答by Ernie Cheng
struct DeviceInfo {
struct Orientation {
// indicate current device is in the LandScape orientation
static var isLandscape: Bool {
get {
return UIDevice.current.orientation.isValidInterfaceOrientation
? UIDevice.current.orientation.isLandscape
: UIApplication.shared.statusBarOrientation.isLandscape
}
}
// indicate current device is in the Portrait orientation
static var isPortrait: Bool {
get {
return UIDevice.current.orientation.isValidInterfaceOrientation
? UIDevice.current.orientation.isPortrait
: UIApplication.shared.statusBarOrientation.isPortrait
}
}
}}
swift4 answer: this is how I do it,
swift4 回答:我就是这样做的,
1.works for all kinds of view controller
1.适用于各种视图控制器
2.also work when the user rotates the app
2.当用户旋转应用程序时也工作
3.also for the first time install the app
3.也是第一次安装app
回答by FBC
Swift 4:
斯威夫特 4:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
print("landscape")
} else {
print("portrait")
}
}
回答by Usman Nisar
To find current device orientation simply use this code:
要查找当前设备方向,只需使用以下代码:
UIApplication.sharedApplication().statusBarOrientation
UIApplication.sharedApplication().statusBarOrientation
for swift 3.0
快速 3.0
UIApplication.shared.statusBarOrientation
UIApplication.shared.statusBarOrientation
回答by Rob
So, if Apple is deprecating the whole orientation string thing ("portrait","landscape"), then all you care about is the ratio of width to height. (kinda like @bpedit's answer)
因此,如果 Apple 不赞成使用整个方向字符串(“portrait”、“landscape”),那么您所关心的只是宽度与高度的比率。(有点像@bpedit 的回答)
When you divide the width by the height, if the result is less than 1, then the mainScreen or container or whatever is in "portrait" "mode". If the result is greater than 1, it's a "landscape" painting. ;)
当您将宽度除以高度时,如果结果小于 1,则主屏幕或容器或处于“纵向”“模式”的任何内容。如果结果大于 1,则为“风景”画。;)
override func viewWillAppear(animated: Bool) {
let size: CGSize = UIScreen.mainScreen().bounds.size
if size.width / size.height > 1 {
print("landscape")
} else {
print("portrait")
}
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
if size.width / size.height > 1 {
print("landscape")
} else {
print("portrait")
}
}
(I'm guessing that if you use this approach then you probably don't really care about specifically handling the condition when the ratio is exactly 1, equal width and height.)
(我猜如果你使用这种方法,那么当比率正好是 1,宽度和高度相等时,你可能并不真正关心具体处理条件。)
回答by bpedit
I had issues with using InterfaceOrientation
, it worked OK except it wasn't accessing the orientation on loading. So I tried this and it's a keeper. This works because the bounds.width
is always in reference to the current orientation as opposed to nativeBounds.width
which is absolute.
我在使用时遇到了问题InterfaceOrientation
,它工作正常,只是它没有访问加载方向。所以我尝试了这个,它是一个守门员。这是有效的,因为bounds.width
始终参考当前方向,而不是nativeBounds.width
绝对方向。
if UIScreen.mainScreen().bounds.height > UIScreen.mainScreen().bounds.width {
// do your portrait stuff
} else { // in landscape
// do your landscape stuff
}
I call this from willRotateToInterfaceOrientation(toInterfaceOrientation:
UIInterfaceOrientation, duration: NSTimeInterval)
and from viewDidLoad
but it flexible.
我称之为 from willRotateToInterfaceOrientation(toInterfaceOrientation:
UIInterfaceOrientation, duration: NSTimeInterval)
and fromviewDidLoad
但它灵活。
Thanks to zSprawl for the pointer in that direction. I should point out that this is only good for iOS 8 and later.
感谢 zSpurwl 提供了指向那个方向的指针。我应该指出,这仅适用于 iOS 8 及更高版本。
回答by stakovereser
Swift 3+
斯威夫特 3+
Basically:
基本上:
NotificationCenter.default.addObserver(self, selector: #selector(self.didOrientationChange(_:)), name: .UIDeviceOrientationDidChange, object: nil)
@objc func didOrientationChange(_ notification: Notification) {
//const_pickerBottom.constant = 394
print("other")
switch UIDevice.current.orientation {
case .landscapeLeft, .landscapeRight:
print("landscape")
case .portrait, .portraitUpsideDown:
print("portrait")
default:
print("other")
}
}
:)
:)
回答by Akarsh SEGGEMU
I found that the alternative code in Swift for the Obj-C code
我发现 Swift 中 Obj-C 代码的替代代码
if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
is
是
if UIApplication.shared.statusBarOrientation.isLandscape
Note: we are trying to find the status bar orientation is landscape or not. If it is landscape then the if statement is true.
注意:我们试图找到状态栏方向是否为横向。如果是横向,则 if 语句为真。