在应用程序扩展中检测方向的最佳方式是什么?

在应用程序扩展中检测设备方向的最佳方法是什么? 我在这里find的解决scheme有着不同的结果:

如何在iOS 8中检测自定义键盘扩展中的方向更改?

获取设备当前方向(应用程序扩展)

我已经看过大小类和UITraitCollection ,发现设备不正确地报告,它是在纵向时,实际上是在景观(不知道这是操作系统错误,或者我不是正确的查询正确的API)。

什么是完成的最佳方法:

  • 首次加载扩展时设备的当前方向
  • 设备将旋转到的方向
  • 设备旋转到的方向

谢谢,

我面对这个问题,也看看你的例子,但没有一个好的解决scheme。 我如何解决它:我创build了一个类,它对UIScreen值进行一些计算,并返回自定义的设备方向。

类标题:

 typedef NS_ENUM(NSInteger, InterfaceOrientationType) { InterfaceOrientationTypePortrait, InterfaceOrientationTypeLandscape }; @interface InterfaceOrientation : NSObject + (InterfaceOrientationType)orientation; @end 

执行:

 @implementation InterfaceOrientation + (InterfaceOrientationType)orientation{ CGFloat scale = [UIScreen mainScreen].scale; CGSize nativeSize = [UIScreen mainScreen].currentMode.size; CGSize sizeInPoints = [UIScreen mainScreen].bounds.size; InterfaceOrientationType result; if(scale * sizeInPoints.width == nativeSize.width){ result = InterfaceOrientationTypePortrait; }else{ result = InterfaceOrientationTypeLandscape; } return result; } @end 

我把它放到viewWillLayoutSubviews或viewDidLayoutSubviews方法来捕捉方向更改事件。

 if([InterfaceOrientation orientation] == InterfaceOrientationTypePortrait){ // portrait }else{ // landscape } 

如果您想获得设备方向的精确的一面(左侧,右侧,上下颠倒),这种方法将无法解决您的问题。 它只是返回纵向或横向的方向。

希望它会帮助你。

您可以通过在UIApplicationWillChangeStatusBarOrientationNotification上添加观察者,然后按如下所示提取方向来获取扩展设备方向。

 - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationWillChange:) name:UIApplicationWillChangeStatusBarOrientationNotification object:nil]; } - (void)orientationWillChange:(NSNotification*)n { UIInterfaceOrientation orientation = (UIInterfaceOrientation)[[n.userInfo objectForKey:UIApplicationStatusBarOrientationUserInfoKey] intValue]; if (orientation == UIInterfaceOrientationLandscapeLeft) //handle accordingly else if (orientation == UIInterfaceOrientationLandscapeRight) //handle accordingly else if (orientation == UIInterfaceOrientationPortraitUpsideDown) //handle accordingly else if (orientation == UIInterfaceOrientationPortrait) //handle accordingly } 

谢谢