iOS中實現(xiàn)單個頁面支持橫豎屏(其他頁面只能豎屏)

一直APP都是只支持豎屏的,現(xiàn)在需求是一個界面要支持橫屏,于是在網(wǎng)上找到的解決方案,這里記錄一哈:

1 首先需要Xcode中選中支持的屏幕方向

image

2 .

在Appdelegate中 .h

@property (nonatomic,assign)NSInteger allowRotate;

.m中

//此方法會在設備橫豎屏變化的時候調(diào)用
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
     if (_allowRotate == 1) {
        return UIInterfaceOrientationMaskAll;
    }else{
        return (UIInterfaceOrientationMaskPortrait);
    }
}
// 返回是否支持設備自動旋轉(zhuǎn)
- (BOOL)shouldAutorotate
{
    if (_allowRotate == 1) {
        return YES;
    }
    return NO;
}

3 在需要支持橫豎屏的controller中:

viewWillApplear 中

//在視圖出現(xiàn)的時候,將allowRotate改為1,
 AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
delegate.allowRotate = 1;

viewWillDisappear中

//在視圖出現(xiàn)的時候,將allowRotate改為0,
 AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
   delegate.allowRotate = 0;

寫好以上代碼之后, 會發(fā)現(xiàn)一些問題: 當橫屏頁面直接點擊“返回”按鈕退出的時候, 頁面依然是橫屏, 而我們需要的是僅一個頁面可以橫屏,測試需要在viewWillDisappear中加入如下代碼:

if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }

此時就可以使app僅有設置頁面支持橫豎屏了!
此時如果app要求用戶在橫屏 豎屏的模式下改變UI(橫屏與豎屏對應不同的UI), 可以在以下方法中執(zhí)行

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    // do something before rotation  
  if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        屏幕從豎屏變?yōu)闄M屏時執(zhí)行
    }else{
        屏幕從橫屏變?yōu)樨Q屏時執(zhí)行
    }
  }
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    // do something after rotation
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

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