首先,在AppDelegate中写下这段代码。这非常重要。
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
return (UIInterfaceOrientationMaskAll);
}
如果您只需要 UIViewController 的 PORTRAIT 模式,请编写以下函数
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
return (UIInterfaceOrientationMaskPortrait);
}
对于需要横屏的UIViewController,将掩码更改为All。
- (NSUInteger)supportedInterfaceOrientations
{
return (UIInterfaceOrientationMaskAllButUpsideDown);
}
如果您想在方向更改时进行一些更改,则可以使用此函数。
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
}
编辑:
很多情况取决于您的UIViewController嵌入在哪个控制器中。
例如,如果它位于UINavigationController内部,则可能需要子类化该UINavigationController以覆盖方向方法,如下所示。
子类化UINavigationController(层次结构中的顶级视图控制器将控制方向)。将其设置为self.window.rootViewController。
- (BOOL)shouldAutorotate
{
return self.topViewController.shouldAutorotate;
}
- (NSUInteger)supportedInterfaceOrientations
{
return self.topViewController.supportedInterfaceOrientations;
}
iOS 6开始,UINavigationController不再向其UIVIewControllers询问方向支持。因此我们需要对其进行子类化。