【发布时间】:2015-01-15 15:27:00
【问题描述】:
现在UIViewController 中的interfaceOrientation 属性已被弃用,检测当前设备方向的推荐方法是什么?
【问题讨论】:
标签: ios uiviewcontroller ios8 uikit uiinterfaceorientation
现在UIViewController 中的interfaceOrientation 属性已被弃用,检测当前设备方向的推荐方法是什么?
【问题讨论】:
标签: ios uiviewcontroller ios8 uikit uiinterfaceorientation
您可以使用[UIApplication sharedApplication].statusBarOrientation
注意[[UIDevice currentDevice] orientation] 不完全像您的应用程序轮换。文档:
讨论: 该属性的值是一个常数,指示设备的当前方向。此值表示设备的物理方向,可能与应用程序用户界面的当前方向不同。有关可能值的说明,请参阅 UIDeviceOrientation。
我会检查 statusBarOrientation 是否有效。
【讨论】:
在 Swift 中,您可以使用
let orientation: UIInterfaceOrientation = UIApplication.shared.statusBarOrientation
【讨论】:
UIApplication.sharedApplication().statusBarOrientation 有效,除非你从
func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
它先于对新 statusBarOrientation 的更改
所以如果你使用 viewWillTransitionToSize 来更新 基于方向(而不是尺寸等级)的设备你被搞砸了 并且必须使用这样的东西
extension UIViewController {
public var orientation : UIInterfaceOrientation? {
let orientation = UIDevice.currentDevice().orientation
var converted : UIInterfaceOrientation!
// UIApplication.sharedApplication().statusBarOrientation is trash cause it lags (being set to the value predating the transition reported by viewWillTransitionToSize)
switch orientation {
case .Portrait: // Device oriented vertically, home button on the bottom
converted = .Portrait
case .PortraitUpsideDown: // Device oriented vertically, home button on the top
converted = .PortraitUpsideDown
case .LandscapeLeft: // Device oriented horizontally, home button on the right
converted = .LandscapeLeft
case .LandscapeRight: // Device oriented horizontally, home button on the left
converted = .LandscapeRight
default:
// let the caller do the dirty dancing with the status bar orientation or whatever
return nil
}
return converted
}
}
你会这样使用:
// willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) is deprecated.
// thusly I have to use the size classes method and compute interface orientation from the device orientation
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
guard let converted = orientation else {
// alert("something else that I do not [need to] handle")
return
}
if converted.isLandscape {
adjustViewsForOrientation(converted, withTransitionCoordinator: coordinator)
} else if converted.isPortrait {
adjustViewsForOrientation(converted, withTransitionCoordinator: coordinator)
}
}
我不知道如何摆脱这个(糟糕的)勇敢的新世界 令人信服的苹果将不赞成使用 willRotateToInterfaceOrientation 就像他们对 autoresizingMask 所做的一样 (除非他们有理由不弃用 autoresizingMask ;-)
或者将 interfaceorientation 作为第三个参数注入 viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
【讨论】:
适用于 iPad
[[UIDevice currentDevice] orientation];
【讨论】:
UIInterfaceOrientation相同