ios - UITabBarController 和 UINavigationController 中特定 UIViewController 中的设备旋转

标签 ios swift swift2

基本上,这是我的页面结构,其中:

TBC = UITabBarController; VC = UIViewController; NVC = UINavigationViewController

                  +--> [NVC] --> [VC] --> ... --> [VC]
 Home             |
 [VC] --> [TBC] --+--> [NVC] --> [VC] --> ... --> [VC]
                  |
                  +--> [NVC] --> [VC] --> ... --> [VC]

并且我希望允许某些特定的 VC 在不同的方向上查看。最有可能的是,这些将是叶节点 VC。它可能是一个用于显示图片或其他内容的页面。

大多数应用只能以纵向方式查看。想想 Facebook 应用程序,其中大部分核心页面都是纵向查看的,图片/视频可以纵向或横向查看。

最佳答案

我的解决方案基于 this answer .

AppDelegate.swift 中:

func application (application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
  return checkOrientation(self.window?.rootViewController)
}

checkOrientation 函数:

func checkOrientation (viewController: UIViewController?) -> UIInterfaceOrientationMask {
  if viewController == nil {
    return UIInterfaceOrientationMask.Portrait

  } else if viewController is MyViewController {
    return UIInterfaceOrientationMask.AllButUpsideDown

  } else if viewController is MyTabBarController {
    if let tabBarController = viewController as? MyTabBarController,
           navigationViewControllers = tabBarController.viewControllers as? [MyNavigationController] {
      return checkOrientation(navigationViewControllers[tabBarController.selectedIndex].visibleViewController)
    } else {
      return UIInterfaceOrientationMask.Portrait
    }

  } else {
    return checkOrientation(viewController!.presentedViewController)
  }
}

使用 if/else 和递归的逻辑可以改进,但目前可以使用。

如果上一个/下一个 UIViewController 必须强制定向,您应该将此行添加到当前 UIViewControllerviewWillDisappear 方法。这将强制上一个/下一个 View

override func viewWillDisappear (animated: Bool) {
  super.viewWillDisappear(animated)
  UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation")
}

关于ios - UITabBarController 和 UINavigationController 中特定 UIViewController 中的设备旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34869507/

相关文章:

swift - 从 Swift 调用 C 可变参数函数

swift - 将具有多个泛型类型的枚举作为参数传递

swift - Xcode 7 - 引用 XCUIElement 的奇怪转换错误

带有结构/协议(protocol)的 Swift 多态闭包分派(dispatch)

ios - 在 swift iOS 中管理用户登录 segues

swift - 将 NSViewController 设置为全屏

ios - 如何使 View Controller 转到随机 View Controller

ios - 0到1之间的swift随机双数

iOS VOIP 应用程序在后台不接受新的套接字连接

ios - 从 CGPoints 数组创建 CGContext