我正在考虑仅针对 iOS 6.0 及更高版本进行轮换。在这里为 UINaviagtionController 创建类别可能是一个好方法。所以按照这些步骤
步骤 1. 将此代码放入您的 AppDelegate.m
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
return UIInterfaceOrientationMaskAll;
}
步骤 2. 为 UINaviagtionController 创建一个类别
方向.h
#import <Foundation/Foundation.h>
@interface UINavigationController (Orientation)
@end
方向.m
#import "Orientation.h"
@implementation UINavigationController (Orientation)
- (BOOL)shouldAutorotate {
if (self.topViewController != nil)
return [self.topViewController shouldAutorotate];
else
return [super shouldAutorotate];
}
- (NSUInteger)supportedInterfaceOrientations {
if (self.topViewController != nil)
return [self.topViewController supportedInterfaceOrientations];
else
return [super supportedInterfaceOrientations];
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
if (self.topViewController != nil)
return [self.topViewController preferredInterfaceOrientationForPresentation];
else
return [super preferredInterfaceOrientationForPresentation];
}
第 3 步。现在创建一个强制初始方向的 UIViewController 类。肖像
PortraitVC.h
#import <UIKit/UIKit.h>
@interface PortraitVC : ViewController
@end
肖像VC.m
- (BOOL)shouldAutorotate
{
return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
同样对于景观
景观VC.h
#import <UIKit/UIKit.h>
@interface LandscapeVC : ViewController
@end
景观VC.m
- (BOOL)shouldAutorotate
{
return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskLandscape;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationLandscapeLeft;
}
第 4 步。现在您想要强制在纵向模式下且不进行旋转的原始 ViewController,在您的 viewDidLoad 中编写此代码
PortraitVC *c = [[PortraitVC alloc] init];
[self presentViewController:c animated:NO completion:NULL];
[self dismissViewControllerAnimated:NO completion:NULL];
并像这样设置方向
- (BOOL)shouldAutorotate
{
return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
如果您只想在横向模式下强制原始 ViewController 不进行旋转,请在 viewDidLoad 中编写此代码
LandscapeVC *c = [[LandscapeVC alloc] init];
[self presentViewController:c animated:NO completion:NULL];
[self dismissViewControllerAnimated:NO completion:NULL];
并像这样设置方向
- (BOOL)shouldAutorotate
{
return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskLandscape;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationLandscapeLeft;
}
我这样做是因为只有当我们使用 presentViewController 或 presentModalViewController 时才会调用“preferredInterfaceOrientationForPresentation”。并且必须调用“preferredInterfaceOrientationForPresentation”来设置初始方向。
希望这可以帮助。