添加一个新的Objective-C类(UINavigationController的子类),并将以下代码添加到.m文件中。
-(NSUInteger)supportedInterfaceOrientations
{
NSLog(@"supportedInterfaceOrientations = %d ", [self.topViewController supportedInterfaceOrientations]);
return [self.topViewController supportedInterfaceOrientations];
}
-(BOOL)shouldAutorotate
{
return self.topViewController.shouldAutorotate;
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return [self.topViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}
在添加新类之后,转到您的ViewController类并进行以下更改。
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
![enter image description here](https://istack.dev59.com/AbXIG.webp)
在 shouldAutorotate 方法和 shouldAutorotateToInterfaceOrientation 方法中,如果您希望 ViewController 支持多种方向,请返回 YES,否则返回 NO。同时,在 shouldAutorotateToInterfaceOrientation 方法中,指定您希望该特定 ViewController 使用的方向。对于所有的视图控制器都要重复这个步骤。
这样做的原因:
1:虽然您可以更改任何 viewController 的 preferredInterfaceOrientationForPresentation 属性以指定特定的方向,但由于您正在使用 UINavigationController,您还需要覆盖其 supportedInterfaceOrientations 属性。
2:为了覆盖 UINavigationController 的 supportedInterfaceOrientations 属性,我们创建了 UINavigationController 的子类并修改与 UINavigation 方向相关的方法。
希望这能帮助您!