ios - 来回切换时锁定的 ViewController 方向中断

标签 ios swift orientation appdelegate

我有一个简单的相机应用程序。 Camera Preview 屏幕是一个 viewcontroller(名称 ViewController),我通过它锁定了方向 此代码(找不到此代码的 StackOverflow 链接),viewcontroller 嵌入在导航 Controller 中:

 func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if let navigationController = self.window?.rootViewController as? UINavigationController {
            if navigationController.visibleViewController is ViewController {
                return UIInterfaceOrientationMask.portrait
            } else {
                return UIInterfaceOrientationMask.all
            }
        }
        return UIInterfaceOrientationMask.portrait
    }

当相机启动时,相机预览锁定在纵向方向,这正是我想要的。 但是,如果我点击库按钮,它会将我转到另一个屏幕, 并通过旋转我的物理设备来更改库屏幕的方向,然后通过“后退”按钮返回到我的相机预览屏幕,方向被破坏了。它处于横向模式,而不是纵向模式。 我如何获得硬锁?

为了以防万一,我在这里制作了一个我的代码的虚拟模型(太长了,无法在这里发布),你们可以自己测试一下

https://github.com/bigmit2011/Testing-Camera

编辑:

如果应用程序崩溃,请尝试再运行一次。 由于某种原因,应用程序第一次运行时崩溃了。谢谢。

编辑2:

尝试将嵌入式 ViewController 设置为 UINavigationController 的委托(delegate)。 但是,我不太明白我是否做对了:

class ViewController: UIViewController, UINavigationControllerDelegate {

    var navigation: UINavigationController?
    self.navigation.delegate = self  // doesn't seem to work


    func navigationControllerSupportedInterfaceOrientations(_ navigationController: UINavigationController) -> UIInterfaceOrientationMask {

        return .portrait
    }

我需要为 UiNavigationController 创建一个单独的 swift 文件吗?

编辑3: 按照马特的回答代码如下:

class CameraViewController :UIViewController, UINavigationControllerDelegate {

override func viewDidLoad() {

    self.navigationController?.delegate = self
    super.viewDidLoad()

func navigationControllerSupportedInterfaceOrientations(_ navigationController: UINavigationController) -> UIInterfaceOrientationMask {

        return .portrait
    }

但是,这似乎将所有内容都锁定为纵向模式,而不仅仅是嵌入在导航 Controller 中的单个 viewController。

最佳答案

你犯了两个错误。

  • 首先,您要尝试从应用委托(delegate)管理各个 View Controller 的方向。那是错误的。应用委托(delegate)管理整个应用的所有可能方向。但是对于 View Controller ,每个单独的 View Controller 都控制着它自己的方向。只需在您的两个 View Controller (而不是在应用程序委托(delegate)中)中的每一个中实现 supportedInterfaceOrientations

  • 其次,您的第一个 View Controller 位于导航界面中。因此它不是顶层 View Controller 并且不能直接管理方向(使用 supportedInterfaceOrientations)。管理导航界面方向的正确方法是将自己设置为导航 Controller 的委托(delegate)并实现navigationControllerSupportedInterfaceOrientations(_:)

关于ios - 来回切换时锁定的 ViewController 方向中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51804089/

相关文章:

ios - Swift:打开和关闭应用程序时不保存/加载用户默认值

iPhone游戏横向方向问题

ios - willRotateToInterfaceOrientation 和 deviceOrientationDidChange 之间有什么区别?

Flutter:如何防止设备方向变化和强制纵向?

ios - UIWindow 的 rootViewController 注意事项

ios - 在 plist 字符串中添加变量

ios - 更改日期较早的单元格的背景颜色

ios - 如何将现有的xcode项目转换为静态库

ios - 如何从框架中调配 AppDelegate 的 didReceiveRemoteNotification

ios - UIWebView 不刷新