使用标签栏控制器锁定到纵向的 iOS 旋转



目前正在处理使用标签栏控制器的应用程序。该应用程序根本不会旋转到横向模式 - 所有视图都继承自 baseVieController,在这里我已经实现了:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return true;
}

现在我知道 tabBar 控制器不会旋转,除非它的所有子视图都支持视图尝试旋转到的方向 - 我的问题是:如果我不实现 - (BOOL)应该自动旋转到界面方向:(UIInterfaceOrientation)接口方向方法在所有子视图中,它会将这些子视图锁定为纵向模式,即使我没有将其指定为所需的方向?因此,将整个选项卡栏控制器锁定为纵向。我知道以前有人问过类似的问题,但我找不到这个具体问题的答案。提前谢谢。

您可以旋转视图,只需要像下面这样覆盖骑行:只需在要旋转的视图控制器类中添加代码(此处为"SampleClassName")

@interface UITabBarController (rotation)
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation;
@end

@implementation UITabBarController (rotation)
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if ([self.selectedViewController isKindOfClass:[UINavigationController class]])
    {
        UINavigationController *navController = (UINavigationController *) self.selectedViewController;
        if ([[navController visibleViewController] isKindOfClass:[SampleClassName class]])
            return YES;
    }
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
如果您

正在使用故事板为 IOS 5 进行开发,这将帮助我遇到同样的问题。 通常在情节提要之前,我们可能会将 TabBarController 添加到 uiview 或应用程序委托中。 使用情节提要时,情节提要视图并不总是必须连接到视图控制器。

要修复,请执行此操作

在子类字段类型 UITabBarController 中添加一个新的类文件 objective-c 类

1 - 在情节提要中选择选项卡栏控制器视图

2 - 在自定义类下将 UITabBarController 更改为您新创建的类名,我称我的 MainTabBarViewController

3 - 在您新创建的类中更改此

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
      return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
        if (interfaceOrientation == UIInterfaceOrientationPortrait)
            return YES;
        if (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
            return YES;
        return NO;
}

基本上,正在发生的事情是您在Interface Builder中创建一个结构,但这只能使您完成部分工作。 在这种情况下,您仍然需要创建配套代码。 起初这让我感到困惑,因为我习惯于 使用 .xib 从头开始构建视图,并且通常会从 appdelegate 配置选项卡栏控制器。

您也可以像这样有条件地控制其中的每一个

if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
    return NO;
if (interfaceOrientation == UIInterfaceOrientationLandscapeRight)
    return NO;
if (interfaceOrientation == UIInterfaceOrientationPortrait)
    return YES;
if (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    return YES;

只需为您想要的返回"是",对不想要的返回"否"。 或者接受一切返回是.

就您的父视图控制器(在您的情况下 - baseViewController)实现此方法而言 -

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return true;
}
您无需在子视图控制器

中实现此功能,因为它支持所有子视图控制器中的所有方向。

最新更新