iPhone - 仅允许一个视图控制器支持横向方向

10

我有一个基于导航的应用程序,其中我希望只有一个视图控制器支持横向模式。 对于该视图控制器(vc1),在 shouldAutorotate 中,我对所有方向都返回 YES,在其他控制器中,我仅对纵向模式返回 YES。

但即使如此,如果设备处于横向模式,并且我从 vc1 转到下一个屏幕,下一个屏幕也会以横向模式旋转。 我假设如果我仅对纵向模式返回 YES,则屏幕应仅以纵向显示。

这是预期的行为吗?我该如何实现我想要的效果?

谢谢。


可能是重复问题:https://dev59.com/KnVC5IYBdhLWcg3wykej - mbauman
我不想设定方向。我只希望其中一种视图不会响应方向的改变。 - lostInTransit
类似的编程问题也出现在http://stackoverflow.com/questions/2041884/problem-with-uiviewcontroller-orientation/2042040#2042040,但是没有添加任何答案。 - Madhup Singh Yadav
3个回答

24

如果您使用UIViewController的shouldAutorotateToInterfaceOrientation方法,则无法仅支持一个视图控制器的横向方向。
您只有两个选择,即所有视图控制器都支持横向或不支持任何视图控制器。

如果要仅为一个视图控制器支持横向,请检测设备旋转并手动旋转视图控制器中的视图。
您可以使用通知来检测设备旋转。

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(didRotate:)
                                             name:UIDeviceOrientationDidChangeNotification
                                           object:nil];

那么,当你检测到设备旋转时,你可以旋转你的视图。

- (void)didRotate:(NSNotification *)notification {
    UIDeviceOrientation orientation = [[notification object] orientation];

    if (orientation == UIDeviceOrientationLandscapeLeft) {
        [xxxView setTransform:CGAffineTransformMakeRotation(M_PI / 2.0)];
    } else if (orientation == UIDeviceOrientationLandscapeRight) {
        [xxxView setTransform:CGAffineTransformMakeRotation(M_PI / -2.0)];
    } else if (orientation == UIDeviceOrientationPortraitUpsideDown) {
        [xxxView setTransform:CGAffineTransformMakeRotation(M_PI)];
    } else if (orientation == UIDeviceOrientationPortrait) {
        [xxxView setTransform:CGAffineTransformMakeRotation(0.0)];
    }
}

1
这正是我所需要的,请问如何旋转UIToolBar和UINavigationBar? - Sam
1
这个非常有效。但是状态栏仍然有一个问题?我该如何跟随设备方向旋转它? - Ajay Sharma

5

我也遇到过这样的情况,当我需要所有视图控制器都以纵向模式显示时,其中一个视图控制器可以旋转到横向模式。而且这个视图控制器还有一个导航栏。

为此,我创建了第二个窗口,我的情况下是相机视图控制器。当我需要显示相机视图控制器时,我显示相机窗口,并在需要推送其他视图控制器时隐藏它。

你还需要将以下代码添加到AppDelegate中。

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{   
    if (window == self.cameraWindow)
    {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    }

    return UIInterfaceOrientationMaskPortrait;
}

0

我在开发我的应用程序时,建议您使用这个解决方案。通过在shouldAutorotateToInterfaceOrientation方法的方向类型中使用一些条件,我们可以解决这个问题。只需尝试使用此链接即可帮助您。

https://dev59.com/pWfWa4cB1Zd3GeqPg22o#15403129


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