这是前提:
以下为步骤:
1.AppDelegate
新加属性 :
@property (nonatomic, assign) BOOL allowRotate;
重写方法:
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
NSLog(@"方向 ============= %d", _allowRotate);
if (_allowRotate) {
return UIInterfaceOrientationMaskAll;
}else{
return (UIInterfaceOrientationMaskPortrait);
}
}
2.公共的BaseTabBarController 、BaseNavigationController中无需添加任何代码
3.公共的BaseViewController重写,然后所有的控制器继承于BaseViewController.。之所以写个公共BaseViewController,好处就是:当需要改变控制器的一些属性时,一改全改
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskPortrait;
}
4.需要横屏的控制器中:主要是在出现之前将 delegate.allowRotate 打开适配所有方向。
//此处需要在 需要 横屏的控制器 显示push或者present之前将AppDelegate中的属性改变,也可以在push或者present之前添加
AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
delegate.allowRotate = YES;
为了解耦代码,我写在了init方法中
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
delegate.allowRotate = YES;
}
return self;
}
//在 push 走或者 dismiss走之前 还原设置,目的是为了push或者dismiss后能恢复竖屏,本来想写在ViewWillDisApeer中,发现有问题,故此改成了如下:
- (IBAction)s:(id)sender {
AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
delegate.allowRotate = NO;
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)pap:(id)sender {
AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
delegate.allowRotate = NO;
[self presentViewController:[JCTest2ViewController new] animated:YES completion:nil];
}
- (BOOL)shouldAutorotate{
return NO;
}
//想要的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskLandscapeRight;
}