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

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

    Actual tested Solution for this.In my example I need my whole app should be in portrait mode, but only one screen's orientation should be in landscape mode.

    Code in AppDelegate as above answers described.

    var orientationLock = UIInterfaceOrientationMask.all
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask 
    {
      return self.orientationLock
    }
    struct AppUtility {  
    
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
    self.lockOrientation(orientation)     
    UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }  
    }
    

    Then write down this code before your landscape orientation viewcontroller will be presented/push.

    override func viewWillAppear(_ animated: Bool) {  
    super.viewWillAppear(animated)
    AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.portrait, andRotateTo: UIInterfaceOrientation.portrait)
    }  
    

    Then write down this code in actual viewcontroller(For landscape view)

    override func viewWillAppear(_ animated: Bool) {  
    super.viewWillAppear(animated)
    AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.landscape, andRotateTo: UIInterfaceOrientation.landscape)
    }  
    

提交回复
热议问题