如何为某些视图控制器锁定 iPhone 的方向 - Swift?

How to lock orientation for iPhone for certain view controllers - Swift?

我有 2 个视图控制器,VC1 和 VC2。

VC1 目前以模态方式呈现 VC2。

VC1 只能纵向,但 VC2 可以有所有方向。

问题是当我在 VC2 中旋转到横向模式然后关闭时,VC1 也处于横向模式!那永远不应该发生!

注意:没有导航控制器或 UITabbarcontroller

我正在下面添加我的代码。

Appdelagate:

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if let rootViewController = self.topViewControllerWithRootViewController(rootViewController: window?.rootViewController) {
        if (rootViewController.responds(to: Selector(("canRotate")))) {
            // Unlock landscape view orientations for this view controller
            return .allButUpsideDown
        }
    }

    // Only allow portrait (standard behaviour)
    return .portrait;
}

private func topViewControllerWithRootViewController(rootViewController: UIViewController!) -> UIViewController? {
    if (rootViewController == nil) { return nil }
    if (rootViewController.isKind(of: (UITabBarController).self)) {
        return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UITabBarController).selectedViewController)
    } else if (rootViewController.isKind(of:(UINavigationController).self)) {
        return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UINavigationController).visibleViewController)
    } else if (rootViewController.presentedViewController != nil) {
        return topViewControllerWithRootViewController(rootViewController: rootViewController.presentedViewController)
    }
    return rootViewController
}

VC2中的代码:

 override func viewDidLoad() {
        super.viewDidLoad()
        UIDevice.current.setValue(Int(UIInterfaceOrientation.portrait.rawValue), forKey: "orientation")
}

func canRotate() -> Void {}

Link 到我寻求帮助并找到这段代码的地方 Website where I found Code

非常感谢您的帮助!

您需要按照以下步骤锁定特定 ViewController 的旋转:-

Step 1: 创建项目时,允许所有方向。不要 select 下图中的任何内容。 Step 2: 如果您希望 VC1 仅实现纵向,请在 ViewController Class

中添加以下两个函数
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.all //return the value as per the required orientation 
    }

override var shouldAutorotate: Bool {
        return false
    }

Step 3: 如果您希望 VC2 具有所有方向,则不要为其添加任何代码。

所以结论:-

在项目设置中,允许整个项目的所有方向。限制应在 ViewController 级别而不是项目级别。

如果您希望任何 VC 具有所有方向,则不要编写任何代码。

如果您希望任何 VC 具有特定方向,请实现上面的两个功能。