shouldAutorotate,supportedInterfaceOrientations和preferredInterfaceOrientationForPresentation在iOS 7中无法正常工作

Mar*_*coz 8 uitabbarcontroller uinavigationcontroller ios7

我在尝试阻止某些视图中的方向时遇到问题,但代码不是工作属性.

我在每个视图中使用这些行:

- (BOOL)shouldAutorotate
{
    return YES;
}

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

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}
Run Code Online (Sandbox Code Playgroud)

它几乎可以在使用UINavigationController的视图中工作,但是在使用UITabBarController的视图中我遇到了很大的问题,因为它接触到的代码没有被调用.

Mar*_*coz 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
Run Code Online (Sandbox Code Playgroud)

现在你只需要使用这个类创建你的TabBarController或你的NavigationController,就像你需要它一样

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

//For the UITabBarController
UITabBarController *tabController = [[cCustomTabController alloc] init];
Run Code Online (Sandbox Code Playgroud)

我希望这能帮到你们.

  • 伙计,你才是天才!谢谢! (4认同)
  • 如果我使用的是Storyboard,我只需要在故事板中将视图控制器的自定义类设置为子类,对吧? (2认同)