2017-05-05 35 views
0

我有2个视图控制器,VC1和VC2。如何锁定某些视图控制器的iPhone方向 - Swift?

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 {} 

链接的地方,我去帮忙,发现这个代码 Website where I found Code

感谢这么多的帮帮我!

+0

你这样做是错的。你在哪里实现['supportedInterfaceOrientations'](https://developer.apple.com/reference/uikit/uiviewcontroller/1621435-supportedinterfaceorientations)?两个视图控制器都必须有一个。 – matt

+0

我目前没有那个地方,因为我尝试过它,它似乎不适用于iOS 10?你能否详细说明一下。对此很新颖!我添加了一个链接,显示我发现代码 – user7097242

+0

'supportedInterfaceOrientations'是iOS 6以后处理设备旋转的首选机制。你没有提到VC1是如何呈现的,但它似乎应该重写该方法来控制它的旋转。 –

回答

5

您需要按照下面的步骤来锁定旋转特定ViewControllers: -

Step 1:在创建项目时,允许所有的方位。不要在下面的图片中选择任何内容。 enter image description here Step 2:如果你想VC1只具有纵向的实现,那么在你的ViewController类

override var supportedInterfaceOrientations: UIInterfaceOrientationMask { 
     return UIInterfaceOrientationMask.all //return the value as per the required orientation 
    } 

override var shouldAutorotate: Bool { 
     return false 
    } 

Step 3:添加以下两个功能。如果你想VC2让所有的方位,然后没有为它添加任何代码。

所以得出的结论: -

在项目设置,允许对整个项目所有的方位。限制应该在ViewControllers级别而不是在项目级别。

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

如果您希望任何VC具有特定的方向,然后执行上述两个函数。

+0

感谢您的帮助!在步骤1)不应该选择所有的东西,以允许所有的方向? – user7097242

+0

默认情况下,如果您不选择任何内容,则允许所有方向。 –

+0

@ user7097242我希望它有帮助,如果它适合您,请接受答案。干杯! –

相关问题