首先,很大程度上取决于您的 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,将遮罩更改为 All。
- (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
否则,如果您希望某些 UIViewController 保持纵向,而其他 UIViewController 支持所有方向,则应用 ALL 蒙版。即 UIInterfaceOrientationMaskAll