防止iOS 11中特定视图控制器中的旋转

时间:2018-11-13 06:36:18

标签: ios swift

我正在尝试防止在特定的VC中旋转(锁定为纵向) 嵌入在导航控制器中。

我目前正在这样做:

到UINavigationController

extension UINavigationController {
    public override func supportedInterfaceOrientations() -> Int {
        return visibleViewController.supportedInterfaceOrientations()
    }
}

在我的VC中:

class ViewController: UIViewController {
    override func supportedInterfaceOrientations() -> Int {
        return Int(UIInterfaceOrientationMask.Landscape.rawValue)
    }
}

但是,当我们转到支持横向和纵向的另一个VC(嵌入在另一个nav控制器中)时,我遇到了问题。假设用户在新屏幕中旋转以横向显示。并单击返回到原始屏幕。现在,该应用以横向显示,而不是在其supportedInterfaceOrientations替代中定义的肖像。如何防止这种错误行为?

我在iOS 11中阅读过,应该使用viewWillTransition(to:with :)处理旋转(以及锁定)。在UIViewController文档中

  

“自iOS 8起,所有与轮换相关的方法都已弃用。代替,   旋转视为视图控制器大小的变化   视图,因此使用viewWillTransition(to:with :)报告   方法。当界面方向改变时,UIKit会调用它   窗口的根视图控制器上的方法。然后那个视图控制器   通知其子视图控制器,传播消息   整个视图控制器层次结构。”

您能指导如何实现吗?

2 个答案:

答案 0 :(得分:2)

您可以使用我一直使用的这个实用工具。

struct AppUtility {

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {

        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }   

    /// OPTIONAL Added method to adjust lock and rotate to the desired orientation
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {

        self.lockOrientation(orientation)

        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }
}

您还可以旋转屏幕,同时将其锁定在该方向。我希望这会有所帮助!

答案 1 :(得分:0)

您可以使用supportedInterfaceOrientationsFor

在您的AppDelegate

中定义

var restrictRotation = Bool()

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if restrictRotation {
        return .portrait
    }
    else {
        return .all
    }
}

在您的ViewController

中放置以下代码
func restrictRotation(_ restriction: Bool) {
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    appDelegate?.restrictRotation = restriction
}

像这样在您的ViewController ViewwillAppear中调用上述函数。

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.restrictRotation(true) // TRUE MEANS ONLY PORTRAIT MODE
              //OR
    self.restrictRotation(false) // FALSE MEANS ROTATE IN ALL DIRECTIONS
}