如何在iOS中支持横向和纵向视图?

时间:2012-10-12 15:12:39

标签: iphone ios uiviewcontroller landscape

在我的应用程序中,我支持单个ViewController的横向和纵向方向。我可以使用Autoresize来支持横向和纵向。但我需要制作与肖像不同的自定义景观。我是iOS新手。在google和SO中搜索了很多但是找不到解决方案。

我正在使用 Xcode 4.5和storyboard 制作视图。

如何支持自定义横向和纵向视图?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

在你的.m文件中试试这个:

- (void)updateLayoutForNewOrientation:(UIInterfaceOrientation)orientation
{
    if (self.interfaceOrientation == UIInterfaceOrientationPortrait || self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        // Portrait

        [object setFrame:CGRectMake(...)];

        // Do the same for the rest of your objects
    }

    else
    {
        // Landscape

        [object setFrame:CGRectMake(...)];

        // Do the same for the rest of your objects
    }
}

在该功能中,您已为视图和横向定义了视图中每个对象的位置。

然后你在viewWillAppear中调用该函数以使其最初工作;视图确定在开始时使用的方向:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self updateLayoutForNewOrientation:self.interfaceOrientation];
}

另外,对于旋转时:

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration 
{    
     [self updateLayoutForNewOrientation:self.interfaceOrientation];
}

如果我需要关于方向的更加个性化的外观,这是我采取的方法。希望这对你有用。

编辑:

如果您使用两个UIViews,一个用于纵向,另一个用于横向,在一个UIViewController中,您可以将代码的第一部分更改为:

- (void)updateLayoutForNewOrientation:(UIInterfaceOrientation)orientation
{
    if (self.interfaceOrientation == UIInterfaceOrientationPortrait || self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        // Portrait

        portraitView.hidden = NO;
        landscapeView.hidden = YES;
    }

    else
    {
        // Landscape

        portraitView.hidden = YES;
        landscapeView.hidden = NO;
    }
}

此编辑的样本与原始样本之间存在利弊。在原始版本中,您必须为每个对象编码,在此编辑的示例中,您只需要此代码,但是,您需要实际分配对象两次,一个用于纵向视图,另一个用于横向视图。

答案 1 :(得分:1)

你仍然可以使用Sean的方法,但由于你有2个不同的视图,你可能有2个不同的Xib文件,所以你可以做一些像[[NSBundle mainBundle] loadNibNamed:"nibname for orientation" owner:self options:nil]; [self viewDidLoad];这样的CGRect部分。我不知道这对于故事板是如何工作的,因为我还没有使用它,但是我在一个需要在方向上需要不同布局的应用程序中这样做,所以我创建了2个Xib文件并将它们连接到ViewController以便在旋转时,加载适当的Xib文件。