第三篇:ios 進入某個VC強轉為橫屏,出VC后復原

今天做項目,某一個VC需要展現VR展覽內容,產品要求這個VC可以橫屏查看,因為橫屏查看的時候,看的范圍比較大,但是其余的VC都是豎屏顯示的,為了達到某個VC橫屏顯示其余VC不變的效果,然后查詢資料,擼代碼。。

查詢過資料之后,大概分為四種實現方式,我使用的是第四種實現方法。

第一種:重寫方法:shouldAutorotate 和supportedInterfaceOrientations

  • 寫一個子類CusNavigationController 繼承 UINavigationController,在CusNavigationController中重寫方法:shouldAutorotate 和 supportedInterfaceOrientations
override var shouldAutorotate: Bool {
        return false
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
  • 在AppDelegate中設置RootViewController為CusNavigationController容器的VC
  • 然后再A里邊重寫shouldAutorotate 和 supportedInterfaceOrientations方法
override var shouldAutorotate: Bool {
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return [.landscapeLeft,.landscapeRight]
    }

這樣的話,就可以支持在A頁面的時候旋轉VC了。

第二種:強制轉換

  • 注意:Apple在3.0以后都不支持這個辦法了,這個辦法已經成為了私有的了,但是要跳過App Stroe的審核,需要一點巧妙的辦法。
//swift3的時候orientation這個參數可能報錯,直接用0,1,2,3代替方向即可
NSNumber *orientationTarget = [NSNumber numberWithInt:orientation];
 [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

第三種:通過人為的辦法改變view.transform的屬性。

第四種:通過appDelgate和第二種方法結合的方式實現

  • 在appdelegate中設置代碼如下:
 /// 設置橫屏/豎屏顯示
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if changeOrientation {
            return [.landscapeLeft,.portrait,.landscapeRight]
        }else {
            return .portrait
        }
    }
  • 然后再需要實現選擇的VC中設置代碼如下:
override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //打開試圖的橫屏顯示
        AppDelegate.shareInstance().changeOrientation = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //將試圖還原為豎屏
        AppDelegate.shareInstance().changeOrientation = false
        UIDevice.current.setValue(NSNumber(value: 1), forKey: "orientation")
    }
  • 再通過實現系統的方法,改變view里邊的布局
override func willAnimateRotation(to toInterfaceOrientation:UIInterfaceOrientation, duration: TimeInterval) {
        if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
            self.standScreen()
        }
        if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
            self.acrossScreen()
        }
    }
    
    func standScreen() {
        contentView?.frame = CGRect(x: 0, y: NavigationBarHeight, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        self.customNavBar?.width = SCREEN_WIDTH
    }
    
    func acrossScreen() { 
       contentView?.frame = CGRect(x: 0, y: NavigationBarHeight, width: SCREEN_HEIGHT, height: SCREEN_WIDTH)
        self.customNavBar?.width = SCREEN_HEIGHT
    }
  • 我這里只有一個webview(contentView)和一個導航欄(self.customNavBar)改變一下frame就可以了
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容