How to lock orientation of one view controller to portrait mode only in Swift

后端 未结 16 2072
梦谈多话
梦谈多话 2020-11-22 12:07

Since my app got support for all orientation. I would like to lock only portrait mode to specific UIViewController.

e.g. assume it was Tabbed Application and when Si

16条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 12:28

    Best Solution for lock and change orientation on portrait and landscape:

    Watch this video on YouTube:

    https://m.youtube.com/watch?v=4vRrHdBowyo

    This tutorial is best and simple.

    or use below code:

    See this picture

    // 1- in second viewcontroller we set landscapeleft and in first viewcontroller we set portrat:

    // 2- if you use NavigationController, you should add extension

    import UIKit
    
    class SecondViewController: UIViewController {
    
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
        }
    
        override open var shouldAutorotate: Bool {
            return false
        }
    
        override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
            return .landscapeLeft
        }
    
        override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
            return .landscapeLeft
        }
        
        
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
    //write The rest of your code in here
    
    
    }
    
    //if you use NavigationController, you should add this extension
    
    extension UINavigationController {
        override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
            return topViewController?.supportedInterfaceOrientations ?? .allButUpsideDown
        
        }
    }
    

提交回复
热议问题