iOS开发系列之终结强制旋转屏幕——OC

最近做项目遇到一个需求,就是大部分页面都是竖屏,只有两个页面是横屏,这就要用到强制旋转屏幕了。我查了网上的资料,人云亦云者众多,但是真正有效的很少,所以干脆我自己总结一个吧,demo见底部,文章里所有代码和设置都是demo里的。

第一步:设置项目属性为只允许竖屏

image.png

需要注意的是,iPad需要在info.plist里设置:

image.png

第二步:AppDelegate里的代码

在 AppDelegate.h里面:

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (nonatomic, strong) UIWindow *window;
@property (assign , nonatomic) BOOL isForceLandscape;
@property (assign , nonatomic) BOOL isForcePortrait;

@end

在 AppDelegate.m里面:

-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    if (self.isForceLandscape) {
        //这里设置允许的横屏类型
        return UIInterfaceOrientationMaskLandscapeRight;
    }else if (self.isForcePortrait){
        return UIInterfaceOrientationMaskPortrait;
    }
    return UIInterfaceOrientationMaskPortrait;
}

第三步:在控制器里的代码,demo是写在控制器的基类BaseViewController里的

在 BaseViewController.h里声明:

@interface BaseViewController : UIViewController
//强制横屏
- (void)forceOrientationLandscape;
//强制竖屏
- (void)forceOrientationPortrait;
@end

在 BaseViewController.m里实现:

//强制横屏
- (void)forceOrientationLandscape {

    AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    appdelegate.isForceLandscape=YES;
    appdelegate.isForcePortrait=NO;
    [appdelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
    //强制翻转屏幕,Home键在右边。
    [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}

//强制竖屏
- (void)forceOrientationPortrait {

    AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    appdelegate.isForcePortrait=YES;
    appdelegate.isForceLandscape=NO;
     [appdelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
    //设置屏幕的转向为竖屏
    [[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}

第四步:使用,demo里是Test1ViewController 使用横屏,TestViewController 使用竖屏:

在 Test1ViewController里使用强制横屏:

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // 强制横屏
    [self forceOrientationLandscape];
}

在 TestViewController里使用强制竖屏:

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //强制旋转竖屏
    [self forceOrientationPortrait];
}

搞定收工,demo地址: https://github.com/zmfflying/ZOrientation

资料参考:
https://www.jianshu.com/p/5c773628caa6

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。