viewDidLoad 中方向报告不正确

3

我有一个应用程序,需要根据设备的方向加载不同的图片作为背景图像。我在viewDidLoad中使用以下代码:

BOOL isLandScape = UIDeviceOrientationIsLandscape(self.interfaceOrientation);

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

由于某种原因,即使模拟器以横向开始,此布尔值仍然为false。我检查了一下,它总是报告处于纵向模式,而不管实际的模拟器方向如何。有人知道为什么这不起作用吗?

在shouldAutoRotateForInterfaceOrientation中,我有以下内容:

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

    return YES;

这段代码是可以正常工作的,只是启动时出了问题。在旋转一次后,它就能正常运行。

2个回答

7
原因是viewDidLoad太早了。每个应用程序都是以竖屏模式启动,然后转换为横屏模式。当调用viewDidLoad时,旋转还没有发生。您需要使用延迟执行或将测试放在didRotateFromInterfaceOrientation或类似位置。请参阅我的书中的说明:

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


我使用了didRotateFromInterfaceOrientation,它起作用了。谢谢! - FreaknBigPanda

2
在函数shouldAutoRotateForInterfaceOrientation中,您只需要return YES
现在使用这个函数。
        -(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
         }

       }

希望这能帮到您


如果每个应用程序都在竖屏模式下启动,那为什么要在viewDidLoad中检查呢? - Kevin Horvath
我怀疑每个应用程序都是以纵向模式启动的。这取决于需求。例如,在iPhone6+,iPhone7+上,您可以在横向模式下使用手机,因此如果用户在横向模式下启动您的应用程序,则“viewdidload”中的代码将负责向用户显示适当的视图,如果他在使用应用程序时更改为纵向模式,则我们有“didRotateFromInterfaceOrientation”来处理它。 - Ajeet Pratap Maurya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接