方向错误地在viewDidLoad中报告

所以我有一个应用程序需要加载不同的图像作为背景图像取决于设备的方向。 我在viewDidLoad中有以下代码:

BOOL isLandScape = UIDeviceOrientationIsLandscape(self.interfaceOrientation); if (isLandScape) { self.bgImage.image = [UIImage imageNamed:@"login_bg748.png"]; } 

由于某些原因,即使模拟器在风景中启动,这个布尔仍然是错误的。 我检查过,无论实际的模拟器方向如何,它总是报告为纵向模式。 有没有人有一个想法,为什么这是行不通的?

在shouldAutoRotateForInterfaceOrientation我有以下几点:

 if (UIDeviceOrientationIsLandscape(interfaceOrientation)) { self.bgImage.image = [UIImage imageNamed:@"login_bg748.png"]; } else { self.bgImage.image = [UIImage imageNamed:@"login_bg1004.png"]; } return YES; 

而这个代码确实工作,它只是一个混乱的启动。 我执行一个旋转后,它工作正常。

原因是viewDidLoad为时尚早。 每个应用程序都以纵向启动,然后旋转到横向。 当viewDidLoad被调用时,旋转还没有发生。 你想使用延迟的性能,或者把你的testing放在didRotateFromInterfaceOrientation或类似的地方。 请参阅我的书中的解释:

http://www.apeth.com/iOSBook/ch19.html#_rotation

首先在函数shouldAutoRotateForInterfaceOrientation你只需要return YES

现在使用这个function

  -(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) { //landscape view login } else { //portrait View logic } } 

如果你已经在横向视图或纵向视图,然后在你的viewDidLoad函数

  -(void)viewDidLoad { if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) { //landscape view code } else { //portrait view code } } 

希望这会有所帮助