我搜索了这个问题的答案,但找不到任何解决我问题的东西。
所以问题来了:我有一个自定义的UINavigationController,在创建它时,supportedInterfaceOrientations
方法在rootViewController上调用(仅支持纵向)。但是当将另一个 ViewController 推送到堆栈上时,此方法不会在推送的 ViewController 上调用(支持除颠倒之外的所有方法)。
我通过在 viewDidLoad
-方法中调用 [self supportedInterfaceOrientations]
来解决它,但我认为这不是解决问题的好方法。
我希望你能在这件事上帮助我。
这是我在第二个视图控制器中实现的代码。
- (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];
}
}
}
我希望这可以帮助其他人解决同样的问题。
您应该在自定义导航控制器中实现这些代码。
- (NSUInteger)supportedInterfaceOrientations {
if ([self.topViewController isMemberOfClass:[RootViewController class]]){
return UIInterfaceOrientationMaskPortrait;
}else{
return UIInterfaceOrientationMaskAllButUpsideDown;
}
}
因为当您的设备旋转时,它会首先询问您的应用程序 rootController(自定义导航控制器),如果那里没有实现supportedInterfaceOrientations
。 然后它会要求根控制器supportedInterfaceOrientations
。
充当主窗口的根视图控制器或在主窗口上全屏显示的视图控制器可以声明它支持的方向。视图控制器编程指南
这在iOS 8中工作正常。
但在iOS 9(Xcode 7)中,我变成了一个警告:"'supportedInterfaceOrientations'实现中的返回类型冲突:'UIInterfaceOrientationMask'(又名'enum UIInterfaceOrientationMask')与'NSUInteger'(又名'unsigned long')"
我已将其更改为:
-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskPortrait;
}
答案的 Swift 版本:
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if self.topViewController is ViewController {
return .Portrait
} else {
return .All
}
}