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直接就是橫屏展示了,我是在這定死了,只能向右橫屏展示,這個可以自己設置的,根據重力展示,如圖:

 

 

 在上架箭頭的地方設置即可!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM