在iPad上确定UIInterfaceOrientation

Jus*_*tin 35 iphone orientation ipad

在这种情况下我不需要指定方向,我只需要检测它,但我遇到了麻烦.我有条件代码,只能在肖像中工作,如果设备在横向,我需要做其他事情.由于deviceOrientation不一定与interfaceOrientation相同,我无法想出一种测试纵向模式的方法.

我在Google上找到的大多数教程都是强制横向或进行某种轮换的方法.我唯一想做的就是确定方向是什么.这是我的代码,它不起作用:

-(void)viewDidLoad {
    [super viewDidLoad];
    //currentOrientation is declared as UIInterfaceOrientation currentOrientation
    currentOrientation = [[UIApplication sharedApplication] statusBarOrientation];
NSLog(@"%@",currentOrientation);  // == NULL
}
Run Code Online (Sandbox Code Playgroud)

我需要有条件地确定interfaceOrientation和program的值.谢谢你的帮助!

zou*_*oul 77

你知道班上的interfaceOrientation财产UIViewController吗?

- (void) viewDidLoad {
    [super viewDidLoad];
    BOOL isPortrait = UIDeviceOrientationIsPortrait(self.interfaceOrientation);
    // now do whatever you need
}
Run Code Online (Sandbox Code Playgroud)

或者你之后[[UIDevice currentDevice] orientation]

  • 我自己也遇到了这个问题.最终的原因是,当视图最初加载时,`self.interfaceOrientation`为'NULL`,因此`UIDeviceOrientationIsPortrait`和`UIDeviceOrientationIsLandscape`都返回NO.在下面的答案中使用`[UIApplication sharedApplication] .statusBarOrientation`始终可以正常工作,因为该方向永远不会为NULL. (4认同)
  • interfaceOrientation首先在iOS 8.0中弃用 (3认同)
  • 请注意,这似乎并不总是有效.特别是如果您的控制器是您应用程序中的第一个.在我的模拟器测试中[self interfaceOrientation]总是返回1.也许它在实际设备上有所不同..至少......难以测试. (2认同)
  • @MusiGenesis:不是这样,正如其他人所说:当应用程序启动时,它经常(在我的情况下,总是)1(肖像).您的(第一个)视图控制器中的interfaceOrientation或[UIApplication sharedApplication]之间没有区别.如果不是,确实*很难在启动时知道UI方向(设备方向在面朝上或朝下时都没有告诉你任何事情). (2认同)

sly*_*rel 41

特别是在发布时,我发现以下内容对于UI始终是准确的,无论UIDevice所说的方向是什么.

[UIApplication sharedApplication].statusBarOrientation
Run Code Online (Sandbox Code Playgroud)


小智 10

self.interfaceOrientation在某些情况下是不可靠的.例如,在tabbar应用程序中重新排列选项卡会返回不正确的值.

[UIApplication sharedApplication].statusBarOrientation总是可靠的.你为我节省了很多时间.谢谢.

  • 值得注意的是,假设statusBarOrientation在执行早期有效是不安全的**.我似乎在didFinishLaunchingWithOptions退出后更新了这个值.那是使用iOS模拟器4.3. (2认同)