iOS強制橫屏


由於項目需求,需要整個項目頁面都是豎屏,唯獨一個折線圖頁面強制性橫屏顯示. 網上逛了許多帖子,也看了好多大神的提供的方法,都沒能夠實現我想要的效果.沒辦法自己研究自己搞,借鑒各路大神的思路,最后費勁千辛萬苦,終於實現了想要的效果。

廢話不多說,上干貨

 

第一步:

Xcode工程配置中的Device Orientation有四個方向,勾選某個方向,即表示支持該方向的旋轉(我這里除了倒置其余三個都選中了)

這一步完成,旋轉手機或者模擬器,畫面就會對應轉換橫豎屏(模擬器模擬轉換方向按鍵為:command+上下左右)

 

第二步:

在AppDelegate中添加方法關閉橫豎屏切換,方法如下

1.AppDelegate.h中外露一個屬性

@property(nonatomic,assign)BOOL allowRotation;//是否允許轉向

 

2.AppDelegate.m中添加方法(如果屬性值為YES,僅允許屏幕向左旋轉,否則僅允許豎屏)

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window

{

    if (_allowRotation == YES) {

        return UIInterfaceOrientationMaskLandscapeLeft;

    }else{

        return (UIInterfaceOrientationMaskPortrait);

    }

}

 

第三步:

1.在需要強制橫屏的控制器.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"];

    }

}

 

2.view DidLoad中添加以下代碼

AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    appDelegate.allowRotation = YES;//(以上2行代碼,可以理解為打開橫屏開關)

[self setNewOrientation:YES];//調用轉屏代碼

 

3.重寫導航欄返回箭頭按鈕,拿到返回按鈕點擊事件

- (void)back

{

    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    appDelegate.allowRotation = NO;//關閉橫屏僅允許豎屏

    [self setNewOrientation:NO];

    [self.navigationController popViewControllerAnimated:YES];

}

大功告成,強制橫屏功能實現,而且重力感應不會轉屏。


免責聲明!

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



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