Force landscape mode in one ViewController using Swift

后端 未结 19 1273
情书的邮戳
情书的邮戳 2020-12-02 07:44

I am trying to force only one view in my application on landscape mode, I am calling

override func shouldAutorotate() -> Bool {
    print(\"shouldAutoro         


        
19条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 08:12

    For me, the best results came from combining Zeesha's answer and sazz's answer.

    Add the following lines to AppDelegate.swift:

    var orientationLock = UIInterfaceOrientationMask.portrait
    var myOrientation: UIInterfaceOrientationMask = .portrait
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return myOrientation
    }  
    

    Add the following line to your view controller class:

    let appDel = UIApplication.shared.delegate as! AppDelegate
    

    Add the following lines to your view controller's viewDidLoad():

    appDel.myOrientation = .landscape
    UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
    

    (optional) Add this line to your dismiss function:

    appDel.myOrientation = .portrait
    UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
    

    What these lines of code do is set the default orientation to portrait, rotate it landscape when the view controller loads, and then finally reset it back to portrait once the view controller closes.

提交回复
热议问题