首先,很大程度上取决于您的 UIViewController 嵌入到哪个控制器中。
例如,如果它在 UINavigationController 中,那么您可能需要继承该 UINavigationController 以覆盖这样的方向方法。
子类 UINavigationController(层次结构的顶部视图控制器将控制方向。)需要将其设置为 self.window.rootViewController。
- (BOOL)shouldAutorotate
{
return self.topViewController.shouldAutorotate;
}
- (NSUInteger)supportedInterfaceOrientations
{
return self.topViewController.supportedInterfaceOrientations;
}
从 iOS 6 开始,UINavigationController 不会向其 UIVIewControllers 请求方向支持。因此我们需要对它进行子类化。
而且
然后,对于只需要 PORTRAIT 模式的 UIViewControllers,编写这些函数
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
return (UIInterfaceOrientationMaskPortrait);
}
对于也需要 LANDSCAPE 的 UIViewController,将遮罩更改为全部。
- (NSUInteger)supportedInterfaceOrientations
{
return (UIInterfaceOrientationMaskAllButUpsideDown);
//OR return (UIInterfaceOrientationMaskAll);
}
现在,如果您想在方向更改时进行一些更改,请使用此功能。
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
}
很重要
在 AppDelegate 中,写这个。这是非常重要的。
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
return (UIInterfaceOrientationMaskAll);
}
如果您只想为所有视图控制器提供肖像模式,请应用肖像蒙版。即UIInterfaceOrientationMaskPortrait
否则,如果您希望某些 UIViewControllers 保持为 Portrait,而其他 UIViewControllers 支持所有方向,则应用 ALL Mask。即UIInterfaceOrientationMaskAll