1 創(chuàng)建UIDevice的category
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIDevice (Orientation)
/**
* @interfaceOrientation 輸入要強(qiáng)制轉(zhuǎn)屏的方向
*/
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation;
@end
NS_ASSUME_NONNULL_END
@implementation UIDevice (Orientation)
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation{
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
//NSNumber *orientationTarget = [NSNumber numberWithInt:interfaceOrientation];
[[UIDevice currentDevice] setValue:@(interfaceOrientation) forKey:@"orientation"];
}
@end
2 AppDelegate里面設(shè)置屏幕旋轉(zhuǎn)權(quán)限
#pragma mark:旋轉(zhuǎn)屏幕
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{
if (self.allowRotation == YES) {
//橫屏
return UIInterfaceOrientationMaskLandscape;
}else{
//豎屏
return UIInterfaceOrientationMaskPortrait;
}
}
3 目標(biāo)界面ViewDidLoad方法里面添加:
appDelegate.allowRotation = YES;
//調(diào)用橫屏代碼
[UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
3.1 在出現(xiàn)界面和消失界面的方法里面設(shè)置禁用手勢(shì)返回代碼
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//禁用側(cè)滑手勢(shì)方法
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
//開啟側(cè)滑手勢(shì)方法
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
3.2 退出界面的時(shí)候
appDelegate.allowRotation = NO;//關(guān)閉橫屏僅允許豎屏
//切換到豎屏
[UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
//present進(jìn)來(lái)的
[self.navigationController popViewControllerAnimated:YES];
//push進(jìn)來(lái)的
[self dismissViewControllerAnimated:true completion:^{
//
}]