靈活設置橫豎屏,不用區(qū)分Push還是Present,都是可以設置。
第一步
勾選方向.png
在AppDelegate.h
中添加旋轉屬性
/** 是否允許轉向 */
@property(nonatomic,assign) BOOL allowRotation;
在AppDelegate.m
中添加轉屏的代理方法
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window {
if (self.allowRotation == YES) {
//橫屏
return UIInterfaceOrientationMaskLandscape;
}else{
//豎屏
return UIInterfaceOrientationMaskPortrait;
}
}
第二步
設置橫豎屏的核心方法宦言,我是直接把這個方法添加到了UIDevice的分類中,代碼如下:
UIDevice+TFDevice.h
#import <UIKit/UIKit.h>
@interface UIDevice (TFDevice)
/**
* @interfaceOrientation 輸入要強制轉屏的方向
*/
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation;
@end
UIDevice+TFDevice.m
#import "UIDevice+TFDevice.h"
@implementation UIDevice (TFDevice)
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation {
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:interfaceOrientation];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
@end
第三步
在需要設置橫屏的控制器的ViewDidLoad中添加下面代碼:
- (void)viewDidLoad {
[super viewDidLoad];
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//允許轉成橫屏
appDelegate.allowRotation = YES;
//調用橫屏代碼
[UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
// 屏幕常亮(不然會息屏)
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}
需要注意的是push過去的時候變成橫屏,pop出去的時候在設置豎屏融师,此時最好禁用系統(tǒng)的側滑返回手勢。
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//禁用側滑手勢方法
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
//禁用側滑手勢方法
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
push控制器:
//點擊導航欄返回按鈕的時候調用蚁吝,所以Push出的控制器最好禁用側滑手勢:
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = NO;//關閉橫屏僅允許豎屏
//切換到豎屏
[UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
[self.navigationController popViewControllerAnimated:YES];
// 還原
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
present控制器:
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = NO;//關閉橫屏僅允許豎屏
//切換到豎屏
[UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
[self dismissViewControllerAnimated:YES completion:nil];
// 還原
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
到此大功告成, 快試試效果吧.