Iphone UIViewController的UIInterfaceOrientation

Iphone UIViewController的UIInterfaceOrientation,iphone,objective-c,ios,ipad,Iphone,Objective C,Ios,Ipad,我尝试检查当前显示的视图控制器的UIInterfaceOrientation,由于某些原因,它总是返回横向 UIInterfaceOrientation currentOrientation = (UIInterfaceOrientation)[[UIApplication sharedApplication] statusBarOrientation]; if (currentOrientation == UIInterfaceOrientationPortrait)

我尝试检查当前显示的视图控制器的UIInterfaceOrientation,由于某些原因,它总是返回横向

 UIInterfaceOrientation currentOrientation = (UIInterfaceOrientation)[[UIApplication sharedApplication] statusBarOrientation];
            if (currentOrientation == UIInterfaceOrientationPortrait){
                self.scrollView_.colMargin = 50;
            } else {
                self.scrollView_.colMargin = 130;
            }

知道为什么吗?

施法不是魔法。状态栏方向与界面方向使用不同的值。改用当前视图控制器的self.interfaceOrientation属性。

您可以按如下方式检查方向:

UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
    if( orientation == UIDeviceOrientationPortrait ) ...

从iOS UIDevice类参考:

方向

返回设备的物理方向。(只读)

讨论

除非通过调用BegingeratingDeviceOrientationNotifications启用了方向通知,否则此属性的值始终返回0

所以你需要做一些类似的事情:

- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
然后别忘了

    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];

当您查看DIDUNLOAD

时,同样的事情总是会导致肖像。您是否锁定在横向模式?您是否已将设备设置为能够旋转?有很多事情可能会阻止它,但我向您保证,上面的代码工作得非常好:)