iOS設置某個VC只能橫屏,其他VC只能豎屏

2019-4-10

效果:

屏幕旋轉(zhuǎn).gif

一、targets選擇
image.png

二、根控制器(UINavigationController 或 UITabBarController)重寫

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    //判斷當前頂層顯示的是 你要設置橫屏的那個控制器(FireAnimationViewController)
    if([self.selectedViewController isKindOfClass:[UINavigationController class]] && [[(UINavigationController *)[self selectedViewController] topViewController] isKindOfClass:[FireAnimationViewController class]]){
        return UIInterfaceOrientationMaskLandscape;
    }
    else{
        return UIInterfaceOrientationMaskPortrait;
    }
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

三、在要設置橫屏的VC里設置

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
     //首先設置UIInterfaceOrientationUnknown欺騙系統(tǒng),避免可能出現(xiàn)  直接設置無效的情況
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationUnknown] forKey:@"orientation"];
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //首先設置UIInterfaceOrientationUnknown欺騙系統(tǒng),避免可能出現(xiàn)直接設置無效的情況
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationUnknown] forKey:@"orientation"];
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationPortrait] forKey:@"orientation"];

}

重寫view的出現(xiàn)和消失方法 改變設備的方向,主要觸發(fā)根控制器的supportedInterfaceOrientations方法 使屏幕旋轉(zhuǎn),如果不設置,會發(fā)現(xiàn)push進來時VC沒旋轉(zhuǎn),手動旋轉(zhuǎn)屏幕VC才會改變方向,view消失時同理,不設置則會pop出來的時候,vc和上個頁面一樣是橫屏的,手動旋轉(zhuǎ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)容