美文网首页
强制页面方向跳转

强制页面方向跳转

作者: 狂暴的小蜗牛 | 来源:发表于2020-08-15 18:04 被阅读0次

在开发中会有单个界面横屏的情况,遇到这种情况不要慌,我们可以这样做

  1. 选中Portrait Device Orientation - Portrait
  2. AppDelegate

.h中

@property (nonatomic,assign)BOOL landscape;

@property (nonatomic,assign)BOOL portrait;

.m

//UIInterfaceOrientationMask是枚举类型,旋转方向可以根据自己项目需求修改
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.landscape) {
        return UIInterfaceOrientationMaskLandscape;
    }else if (self.portrait) {
        return UIInterfaceOrientationMaskPortrait;
    }
    return UIInterfaceOrientationMaskPortrait;
}
  1. 在需要旋转方向的界面添加#import "AppDelegate.h"
// 是否允许自动旋转-系统方法
-(BOOL)shouldAutorotate{
    return YES;
}

// 旋转屏幕时是否隐藏状态栏-系统方法
-(BOOL)prefersStatusBarHidden{
    return NO;
}

//切换至横屏
-(void)forceOrientationLandscapeWith:(UIViewController *)VC{
    
    AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    appdelegate.portrait=NO;
    appdelegate.landscape=YES;
    [appdelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:VC.view.window];
    
    //强制翻转屏幕,Home键在右边。
    [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}

// 竖屏
- (void)forceOrientationPortraitWith:(UIViewController *)VC{
    
    AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    appdelegate.portrait=YES;
    appdelegate.landscape=NO;
    [appdelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:VC.view.window];
    
    //强制翻转屏幕
    [[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}


需要切换横屏时 执行[self forceOrientationLandscapeWith:self];

需要切换竖屏时 执行[self forceOrientationPortraitWith:self];
  1. 如果在放回或者跳转其他界面时需要重新恢复竖屏
//放回或者跳转其他界面时恢复竖屏显示
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self forceOrientationPortraitWith:self];
}

相关文章

网友评论

      本文标题:强制页面方向跳转

      本文链接:https://www.haomeiwen.com/subject/okiadktx.html