iOS在某個頁面強制橫屏

最近在網(wǎng)上找了很多關于如何在某一個頁面強制橫屏的資料,但是還是沒有實現(xiàn)預期的效果。最后經(jīng)過不懈努力,最終還是找到了一個可以實現(xiàn)這一需求的方法。下面就將該方法整理出來,并附帶demo下載。供以后在開發(fā)中方便使用。

方法實現(xiàn)部分

在AppDelegate.h中定義一個屬性,如下:

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

AppDelegate.m中實現(xiàn)橫屏或豎屏的設置:

///// 如果屬性值為YES,僅允許屏幕向左旋轉(zhuǎn),否則僅允許豎屏。
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {

    if (self.allowRotation == YES) {

        // 橫屏
        return UIInterfaceOrientationMaskLandscape;
    } else {

        // 豎屏
        return (UIInterfaceOrientationMaskPortrait);
    }
}

在UIDevice分類中實現(xiàn)強制轉(zhuǎn)屏,如下:

/// 輸入要強制轉(zhuǎn)屏的方向
/// @param interfaceOrientation 轉(zhuǎn)屏的方向
+ (void)deviceMandatoryLandscapeWithNewOrientation:(UIInterfaceOrientation)interfaceOrientation {
    
    NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];

    [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
    
    // 將輸入的轉(zhuǎn)屏方向(枚舉)轉(zhuǎn)換成Int類型
    int orientation = (int)interfaceOrientation;

    // 對象包裝
    NSNumber *orientationTarget = [NSNumber numberWithInt:orientation];

    // 實現(xiàn)橫豎屏旋轉(zhuǎn)
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}

應用部分

關于應用部分的代碼,在需要旋轉(zhuǎn)屏幕的地方調(diào)用如下方法:

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    // 打開橫屏開關
    appDelegate.allowRotation = YES;
    // 調(diào)用轉(zhuǎn)屏代碼
    [UIDevice deviceMandatoryLandscapeWithNewOrientation:UIInterfaceOrientationLandscapeRight];

在返回到上一個頁面的時候,如果需要保持原來的豎屏,那么就應該實現(xiàn)對應的方法即可:

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    // 關閉橫屏僅允許豎屏
    appDelegate.allowRotation = NO;
    // 切換到豎屏
    [UIDevice deviceMandatoryLandscapeWithNewOrientation:UIInterfaceOrientationPortrait];
    
    [self.navigationController popViewControllerAnimated:YES];

好了,代碼的主要實現(xiàn)部分都已經(jīng)完成了,高高興興的進入調(diào)試階段,結(jié)果怎么也不能實現(xiàn)預期效果。這又是什么原因呢,難道是代碼層面還有什么問題沒處理好?仔細檢查了一下,原來是下面的原因:


QQ20200511-160317.png

沒錯,你只要需要將Requires full screen這個選項鉤上就大功告成了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容