2012-06-11 19 views
4

我需要根据方向更改View的图像背景。对于这一点,我使用viewWillAppear的statusBarOrientation方法:statusBarOrientation在viewWillAppear上的错误值

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 
    UIInterfaceOrientation currentOrientation = [[UIApplication sharedApplication] statusBarOrientation]; 
    if (UIInterfaceOrientationIsPortrait(currentOrientation)) { 
     NSLog(@"PORTRAIT"); 
    } else if (UIInterfaceOrientationIsLandscape(currentOrientation)) { 
     NSLog(@"LANDSCAPE"); 
    } 
} 

的问题是,控制台总是显示人像,甚至当iPad在横向模式举行。 viewDidAppear中的代码正常工作,但已经太晚了,用户可以看到图像的更改。这让我认为statusBarOrientation的正确状态在viewWillAppear中仍然不可用,但我已经阅读过其他一些问题,这些代码应该在那里工作。

+0

什么更奇怪的是,在viewWillTransitionToSize:你可以查询方向,如果你旋转手机两次(回到它的viewDidLoad位置),statusBarOrientation会给你正确的答案。尽管它在viewDidLoad中给出了不同的答案,现在该设备与当时的方向相同! –

回答

12

尝试

int type = [[UIDevice currentDevice] orientation]; 
    if (type == 1) { 
     NSLog(@"portrait default"); 
    }else if(type ==2){ 
     NSLog(@"portrait upside"); 
    }else if(type ==3){ 
     NSLog(@"Landscape right"); 
    }else if(type ==4){ 
     NSLog(@"Landscape left"); 
    } 
+1

好吧,有趣......我到处看到,状态栏方向的方法比UIDevice更可靠,但这就像一个魅力!谢谢! –

+0

不客气 –

+1

我搜索无处不在... interfaceOrientation,statusBar都返回错误的方向,然后这个解决方案工作+1 .. – iMeMyself

3

你不应该使用statusBarOrientation来确定应用程序的当前方位。根据Apple的文档:http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html

此属性的值是一个常数,指示接收方的状态栏的方向。有关详细信息,请参阅UIInterfaceOrientation。设置此属性可将状态栏旋转到指定的方向,而无需为过渡设置动画。但是,如果您的应用程序具有可旋转的窗口内容,则不应该使用此方法任意设置状态栏方向。如果设备更改方向,则通过此方法设置的状态栏方向不会更改。

尝试使用一个UIViewController的interfaceOrientation属性来获取当前应用的方向。

+1

我用这种方法,因为它在几个答案在这里在Stackoverflow推荐获取方向。使用[[UIDevice currentDevice]方向]方式工作。读取属性interfaceOrientation也起作用。 –

+0

Apple文档的链接并没有说你不应该使用它来确定当前的方向。你能否给我们一个参考资料来源,说明你为什么不应该?实际上,Apple的示例代码使用它:https://developer.apple.com/library/content/samplecode/AVCam/Listings/Swift_AVCam_CameraViewController_swift.html#//apple_ref/doc/uid/DTS40010112-Swift_AVCam_CameraViewController_swift-DontLinkElementID_15 Cmd-F for statusbarOrientation。事实上,UIDevice的方向警告说它可能与你的UI的方向不同,所以根据文档判断,应该避免它。 –

+0

这给一些设备带来问题。谢谢苹果。 – Warpzit

0

这里是一个有用的代码段用于记录设备的interfaceOrientation:

NSArray* orientations = @[ @"nothing", @"UIInterfaceOrientationPortrait", @"UIInterfaceOrientationPortraitUpsideDown", @"UIInterfaceOrientationLandscapeLeft", @"UIInterfaceOrientationLandscapeRight”]; 
NSLog(@"Current orientation := %@", orientations[self.interfaceOrientation]); 

希望这有助于有人出来!

相关问题