在iOS 7中,shouldAutorotate、supportedInterfaceOrientations和preferredInterfaceOrientationForPresentation不像预期的那样起作用。

8

我在尝试阻止某些视图的方向,但代码不起作用。

我在每个视图中使用以下代码行:

- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return UIInterfaceOrientationMaskPortrait;
    } else {
        return UIInterfaceOrientationMaskAll;
    }
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

这段代码在使用UINavigationController的视图中几乎可以正常工作,但是在使用UITabBarController的视图中出现了大问题,因为似乎代码没有被调用。

1个回答

14

好的,我解决了,你需要继承UINavigationController和UITabBarController,下面是代码:

//cCustomNavigationController.h file

#import <UIKit/UIKit.h>

@interface cCustomNavigationController : UINavigationController <UINavigationControllerDelegate>

@end

//cCustomNavigationController.m file

#import "cCustomNavigationController.h"

@interface cCustomNavigationController ()

@end

@implementation cCustomNavigationController 

- (BOOL)shouldAutorotate {
    return [self.visibleViewController shouldAutorotate];
}

- (NSUInteger)supportedInterfaceOrientations {
    return [self.visibleViewController supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return [self.visibleViewController preferredInterfaceOrientationForPresentation];
}

@end

//cCustomTabController.h file

#import <UIKit/UIKit.h>

@interface cCustomTabController : UITabBarController <UITabBarControllerDelegate>

@end

//cCustomTabController.m file

#import "cCustomTabController.h"

@interface cCustomTabController  ()

@end

@implementation cCustomTabController

- (BOOL)shouldAutorotate {
    return [self.selectedViewController shouldAutorotate];
}

- (NSUInteger)supportedInterfaceOrientations {
    return [self.selectedViewController supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return [self.selectedViewController preferredInterfaceOrientationForPresentation];
}

@end

现在您只需使用这些类创建您的TabBarController或NavigationController,无论您何时需要它。

//For the UINavigationController
UINavigationController *navigationController = [[cCustomNavigationController alloc] init];

//For the UITabBarController
UITabBarController *tabController = [[cCustomTabController alloc] init];

我希望这能帮助到你们。


4
哥们,你太聪明了!谢谢! - EgorkZe
2
如果我正在使用故事板(Storyboard),我只需要在故事板中将视图控制器(View Controller)的自定义类设置为其子类,是这样吗? - mrd

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