how to lock portrait orientation for only main view using swift

后端 未结 16 1931
野性不改
野性不改 2020-12-07 13:38

I have created an application for iPhone, using swift, that is composed from many views embedded in a navigation controller. I would like to lock the main v

16条回答
  •  广开言路
    2020-12-07 14:11

    This requires two things

    • Informing the controller of its support for rotation.
    • Enforcing rotation and then handing over responsibility to a controller that knows its support for rotation.

    Declare an extension on view controller that forces orientation to portrait.

    extension UIViewController {
    
      func forcePortrait() {
        UIView.setAnimationsEnabled(false)
        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        UIView.setAnimationsEnabled(true)
      }
    
    }
    

    Any view controller that is locked to portrait could inherit traits.

    class PortraitViewController: UIViewController {
    
      override open var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait }
      override open var shouldAutorotate: Bool { return false }
    
      override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        forcePortrait()
      }
    
    }
    

    Any view controller that is capable of rotating between portrait and landscape can inherit those traits.

    class LandscapeViewController: UIViewController {
    
      override open var supportedInterfaceOrientations: UIInterfaceOrientationMask { return [.landscape, .portrait]  }
      override open var shouldAutorotate: Bool { return true }
    
      override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // if leaving for a portrait only screen, force portrait.
        // forcePortrait()
      }
    
    }
    

    If your landscape view controller is about to segue to a portrait locked screen. Be sure to lock the orientation just before leaving. Then rely on the portrait view controller to enforce its own lack of rotation.

提交回复
热议问题