ios开发之 -- 强制横屏

时间:2023-03-09 15:48:27
ios开发之 -- 强制横屏

在写项目的时候,会遇到很多稀奇古怪的需求,我就碰到一个写一个网站,需要强制横屏,然后不需要上架,网上看了很多大神的需求,基本都能实现,但是不太好用,

自己参考搞了一个,代码如下:

AppDelegate.h

@property(nonatomic,assign)BOOL allowRotation;//是否允许转向

.m

#pragma mark 支持窗口翻转
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window { if (_allowRotation == YES) { return UIInterfaceOrientationMaskLandscapeRight; }else{ return (UIInterfaceOrientationMaskPortrait); } }

横屏展示的viewcontroler:

.m

- (void)setNewOrientation:(BOOL)fullscreen

{

    if (fullscreen) {

        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];

        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];

        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];

        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

    }else{

        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];

        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];

        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];

        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

    }

}

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; appDelegate.allowRotation = YES;//(以上2行代码,可以理解为打开横屏开关) [self setNewOrientation:YES];//调用转屏代码 [self creatWebView]; } -(void)creatWebView
{
UIWebView *webV = [[UIWebView alloc]initWithFrame:self.view.frame];
[webV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.badiu.com"]]];
[self.view addSubview:webV];
}

这样的话,进入的vc直接就是横屏展示了,我是在这定死了,只能向右横屏展示,这个可以自己设置的,根据重力展示,如图:

ios开发之 -- 强制横屏

在上架箭头的地方设置即可!