Swift 3 - 强制自动旋转

时间:2016-12-20 00:26:54

标签: ios swift auto-rotation

大家好我正在使用此代码stackoverflow

例如,我有视图1(仅限肖像)和视图2(纵向+横向)。当您在视图1中并单击按钮时,在整个屏幕上打开视图2并弹出窗口,当您关闭视图2并且视图1变为可见时,如果视图2处于横向状态,我希望自动将其转换为纵向模式。有什么建议吗?

1 个答案:

答案 0 :(得分:10)

正如你所说的那样你使用弹出窗口,我确信你正在使用navigationController。这是视图层次结构。

有三个viewControllers对应于那些xib。

viewController仅设置为portrait,secondViewController设置为portrait and landScapeLeft(您可以将其更改为您需要的任何内容)。它可以根据您的要求正常工作。当第二个处于横向时,弹出到第一个,它将被强制设置为纵向。

NavViewController

ViewController

SecondViewController

views hierarchy

// NavViewController.swift

class NavViewController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override var shouldAutorotate: Bool {
        return (visibleViewController?.shouldAutorotate)!
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return (visibleViewController?.supportedInterfaceOrientations)!
    }
}

// ViewController.swift

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override var shouldAutorotate: Bool {
        return false
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let value =  UIInterfaceOrientation.portrait.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation()
    }
}

SecondViewController.swift     class SecondViewController:UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override var shouldAutorotate: Bool {
        return true
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return [.portrait, .landscapeLeft]
    }
}