Force landscape mode in one ViewController using Swift

后端 未结 19 1257
情书的邮戳
情书的邮戳 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:15

    I faced a similar issue in my project. It only has support for portrait. The ViewController structure is that, Navigation contained a controller (I called A), and a long Scrollview in A controller. I need A(portrait) present to B(landscape right).

    In the beginning I tried the method below and it seemed to work but eventually I found a bug in it.

    Swift 5 & iOS12

    // In B controller just override three properties
    
    override var shouldAutorotate: Bool {
        return false
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.landscapeRight
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .landscapeRight
    }
    

    And then something become strange. When controller B dismiss to controller A. The ScrollView in controller A has been slid some point.

    So I used another method, so I rotate the screen when viewWillAppear. You can see the code for that below.

    // In controller B
    // not need override shouldAutorotate , supportedInterfaceOrientations , preferredInterfaceOrientationForPresentation
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let appDel = UIApplication.shared.delegate as! AppDelegate
        appDel.currentOrientation = .landscapeRight
        UIDevice.current.setValue( UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation()
    }
    
    //in viewWillDisappear rotate to portrait can not fix the bug
    
    
    override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
        let appDel = UIApplication.shared.delegate as! AppDelegate
        appDel.currentOrientation = .portrait
        UIDevice.current.setValue( UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation() //must call 
        super.dismiss(animated: true, completion: nil)
    }
    
    // in AppDelegate
    // the info plist is only supported portrait also, No need to change it
    
    var currentOrientation : UIInterfaceOrientationMask = .portrait
    
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return self.currentOrientation
    }
    

提交回复
热议问题