在iOS 7中,supportedInterfaceOrientations方法没有被调用。

4
我搜索了一下,但没有找到解决我的问题的答案。
问题如下: 我有一个自定义的UINavigationController,在创建它时会调用rootViewController上的“supportedInterfaceOrientations”方法(仅支持纵向)。 但是,当将另一个ViewController推入堆栈时,这个方法不会在推送的ViewController上被调用(支持除了倒置以外的所有方向)。
我通过在“viewDidLoad”方法中调用“[self supportedInterfaceOrientations]”来解决了这个问题,但我认为这并不是解决问题的好方法。
希望你能在这个问题上给我帮助。
以下是我在第二个viewController中实现的代码。
- (BOOL)shouldAutorotate {
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        [[[UIApplication sharedApplication] delegate] setGlobalOrientationMask:UIInterfaceOrientationMaskAllButUpsideDown];
        return UIInterfaceOrientationMaskAllButUpsideDown;
    }
    else {
        [[[UIApplication sharedApplication] delegate] setGlobalOrientationMask:UIInterfaceOrientationMaskAll];
        return UIInterfaceOrientationMaskAll;
    }
}

我认为JohnMa的解决方案对于大多数应用程序都有效,但在我的情况下,存在一个特殊问题,我认为需要特别处理,但现在我已经自己解决了(不确定它是否好,但它有效)。

我在我的导航控制器代理中实现了- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated方法。

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (DEF_SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7")) {
        if ([viewController respondsToSelector:@selector(supportedInterfaceOrientations)]) {
            [viewController supportedInterfaceOrientations];
        }
    }
}

我希望这篇文章可以帮助其他遇到相同问题的人。
3个回答

14

你应该将这些代码实现在你的自定义 NavigationController 中。

 - (NSUInteger)supportedInterfaceOrientations {
    if ([self.topViewController isMemberOfClass:[RootViewController class]]){
        return UIInterfaceOrientationMaskPortrait;
    }else{
        return UIInterfaceOrientationMaskAllButUpsideDown;
   }  
 }

当您的设备旋转时,它会首先询问您的应用程序根控制器(自定义导航控制器),如果那里没有实现supportedInterfaceOrientations,则会继续向根控制器询问supportedInterfaceOrientations

作为主窗口的根视图控制器或以全屏方式呈现在主窗口上的视图控制器可以声明其支持的方向。视图控制器编程指南


1
这很有帮助,但是现在出现了一个问题,当从纵向旋转到横向时,第一次旋转会调用我的导航控制器上的supportedInterfaceOrientations方法,但是旋转没有完成,只有当第二次旋转到横向方向时,旋转才能正确完成。 - manuelwaldner
你找到解决第一次/第二次问题的方法了吗?我也遇到了同样的问题。 - Ashish Awaghad

2

这在iOS 8中运行良好。

但在iOS 9(Xcode 7)中,我收到了一个警告:

"supportedInterfaceOrientations的实现中存在冲突的返回类型:'UIInterfaceOrientationMask'(也称为'enum UIInterfaceOrientationMask')与'NSUInteger'(也称为'unsigned long')"

我已将其更改为:

-(UIInterfaceOrientationMask)supportedInterfaceOrientations{  
     return UIInterfaceOrientationMaskPortrait;  
}

0

所选答案的 Swift 版本:

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    if self.topViewController is ViewController {
        return .Portrait
    } else {
        return .All
    }
}

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