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

后端 未结 16 2255
梦谈多话
梦谈多话 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:27

    Add this code to force portrait and lock it:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Force the device in portrait mode when the view controller gets loaded
        UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation") 
    }
    
    override func shouldAutorotate() -> Bool {
        // Lock autorotate
        return false
    }
    
    override func supportedInterfaceOrientations() -> Int {
    
        // Only allow Portrait
        return Int(UIInterfaceOrientationMask.Portrait.rawValue)
    }
    
    override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
    
        // Only allow Portrait
        return UIInterfaceOrientation.Portrait
    }
    

    In your AppDelegate - set supportedInterfaceOrientationsForWindow to whatever orientations you want the entire application to support:

    func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.All
    } 
    

提交回复
热议问题