這是前提:
以下為步驟:
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.需要橫屏的控制器中:主要是在出現(xiàn)之前將 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中膘怕,發(fā)現(xiàn)有問題想诅,故此改成了如下:
- (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;
}