本文介绍了如何使用Swift锁定仅主视图的肖像方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 swift 为iPhone创建了一个应用程序,该应用程序由嵌入在导航控制器中的许多视图组成.我想将主视图锁定为纵向,而将导航控制器的子视图锁定为横向.这是我的意思的示例:

I have created an application for iPhone, using swift, that is composed from many views embedded in a navigation controller. I would like to lock the main view to Portrait orientation and only a subview of a navigation controller locked in Landscape orientation.Here is an example of what i mean:

  • UINavigationController
    • UiViewController1(纵向锁定)初始视图控制器,在导航栏上放置一个按钮,使用户可以访问列表,在列表中可以选择其他视图
    • UIViewController2(锁定为横向模式)
    • UiViewController3(纵向和横向)
    • UiViewController4(纵向和横向)
    • ...
    • ...
    • UINavigationController
      • UiViewController1 (Locked in Portrait) Initial view controller with a button placed on the navigation bar that give to the user the possibility to access to a lists where can be selected other views
      • UIViewController2 (Locked in Landscape)
      • UiViewController3 (Portrait and Landscape)
      • UiViewController4 (Portrait and Landscape)
      • ...
      • ...

      我该怎么做?

      推荐答案

      根据针对supportedInterfaceOrientations的Swift Apple文档:

      According to the Swift Apple Docs for supportedInterfaceOrientations:

      您的导航控制器应覆盖shouldAutorotatesupportedInterfaceOrientations,如下所示.为了方便起见,我在UINavigationController扩展程序中做到了这一点:

      Your navigation controller should override shouldAutorotate and supportedInterfaceOrientations as shown below. I did this in a UINavigationController extension for ease:

      extension UINavigationController {
          public override func shouldAutorotate() -> Bool {
              return true
          }
      
          public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
              return (visibleViewController?.supportedInterfaceOrientations())!
          }
      }
      

      您的主视图控制器(始终为肖像)应该具有:

      And your main viewcontroller (portrait at all times), should have:

      override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
          return UIInterfaceOrientationMask.Portrait
      }
      

      然后,在您的子视图控制器中要支持纵向或横向:

      Then, in your subviewcontrollers that you want to support portrait or landscape:

      override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
          return UIInterfaceOrientationMask.All
      }
      

      已针对iOS 9更新:-)

      这篇关于如何使用Swift锁定仅主视图的肖像方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 21:23