Disable rotation for View Controller in Navigation Controller

前端 未结 7 867
闹比i
闹比i 2020-12-19 12:57

First of all, this isn\'t a duplicate. I\'ve looked at all of the questions related to this on SO and none of them work for me. Hopefully it\'s just because I\'m new to iOS

7条回答
  •  温柔的废话
    2020-12-19 13:24

    My case has 3 view controller:
    - first view controller: portrait
    - second view controller: landscape right (has navigation controller and was presented by first view controller)
    - third view controller: portrait (has navigation controller and was pushed by second view controller )
    And this is my solution in swift 3:
    ------------------------------------
    At AppDelegate:
    - Add this property to save your setting

    private var orientation: UIInterfaceOrientationMask = .portrait
    

    -Then create a function to set rotate for your device:

    func rotateScreen(orientation: UIInterfaceOrientationMask) {
        self.orientation = orientation
        var value = 0;
        if orientation == .landscapeRight {
            value = UIInterfaceOrientation.landscapeRight.rawValue
        }else {
            value = UIInterfaceOrientation.portrait.rawValue
        }
        UIDevice.current.setValue(value, forKey: "orientation")
    }
    

    - Finally, implement support orientation method:

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return self.orientation
    }
    

    --------------------------------
    Then you can call like this before display destination view controller

    (UIApplication.shared.delegate as! AppDelegate).rotateScreen(orientation: .landscapeRight)
    

    For example, in my case: When user tap on button at the First to present the Second, I'll do like this

    (UIApplication.shared.delegate as! AppDelegate).rotateScreen(orientation: .landscapeRight)
    self.present(navigation, animated: true, completion: nil)
    

    And the close button at the Second I'll do like this

    (UIApplication.shared.delegate as! AppDelegate).rotateScreen(orientation: .portrait)
    self.dismiss(animated: true, completion: nil)
    

    That's all! You could never mind using navigation controller or not. Hope this helps you guys ^__^!

提交回复
热议问题