自 iOS8 起,检测 UIViewController 方向的方法已被弃用。
例如 -interfaceOrientation
已经被废弃,为了检测当前视图控制器的方向,似乎需要向视图控制器的 -traitCollection
属性询问此信息。
我有点困惑 iPad 在两个方向上都将其特征设置为正常。
检测当前方向的最佳方法是什么?
自 iOS8 起,检测 UIViewController 方向的方法已被弃用。
例如 -interfaceOrientation
已经被废弃,为了检测当前视图控制器的方向,似乎需要向视图控制器的 -traitCollection
属性询问此信息。
我有点困惑 iPad 在两个方向上都将其特征设置为正常。
检测当前方向的最佳方法是什么?
使用UIDevice
的-orientation
属性是不正确的(即使在大多数情况下它可以工作),可能会导致一些错误,例如UIDeviceOrientation
还考虑设备是否朝上或朝下,UIInterfaceOrientation
枚举中没有这些值的对应项。
此外,如果你锁定你的应用程序在某个特定的方向上,UIDevice
会给出设备方向而不考虑这一点。
另一方面,iOS8已经弃用了UIViewController
类的interfaceOrientation
属性。
有两种选项可以用来检测接口方向:
仍然缺少的是一种了解接口方向更改方向的方法,在动画过程中这非常重要。在WWDC 2014年“iOS8中的视图控制器进阶”会议中,演讲者提供了解决这个问题的方法,使用取代-will/DidRotateToInterfaceOrientation
的方法。
这里提出的解决方案部分实现如下:
-(void) viewWillTransitionToSize:(CGSize)s withTransitionCoordinator:(UIVCTC)t {
orientation = [self orientationFromTransform: [t targetTransform]];
oldOrientation = [[UIApplication sharedApplication] statusBarOrientation];
[self myWillRotateToInterfaceOrientation:orientation duration: duration];
[t animateAlongsideTransition:^(id <UIVCTCContext>) {
[self myWillAnimateRotationToInterfaceOrientation:orientation
duration:duration];
}
completion: ^(id <UIVCTCContext>) {
[self myDidAnimateFromInterfaceOrientation:oldOrientation];
}];
}
查看UIDevice的UIDeviceOrientation部分及其方向属性。文档在这里。这是我进行方向检查的方法。您还可以查看屏幕宽度是否大于屏幕高度,因为有时,在应用程序首次启动时,它将是UIDeviceOrientationUnknown。