【发布时间】:2018-08-11 21:59:58
【问题描述】:
我有一个简单的相机应用程序。 相机预览屏幕是一个视图控制器(名称 ViewController),我通过它锁定了方向 此代码(找不到此代码的 StackOverflow 链接),视图控制器嵌入在导航控制器中:
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
}
当相机启动时,相机预览被锁定在 .portrait 方向,这是我想要的。 但是,如果我点击库按钮,这会将我转到另一个屏幕, 并通过旋转我的物理设备更改库屏幕的方向,然后通过“返回”按钮返回我的相机预览屏幕,方向被破坏。它处于横向模式,而不是纵向模式。 如何获得硬锁?
以防万一,我在这里做了一个我的代码的虚拟模型(这里太长了,不能在这里发布),你们可以自己测试一下
https://github.com/bigmit2011/Testing-Camera
编辑:
如果应用程序崩溃,请尝试再运行一次。 由于某种原因,第一次运行应用程序时它会崩溃。谢谢。
编辑2:
试图将嵌入式 ViewController 设置为 UINavigationController 的委托。 但是,我不太明白我是否正确:
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
}
但是,这似乎将所有内容锁定为纵向模式,而不仅仅是嵌入在导航控制器中的单个 viewController。
【问题讨论】:
-
你的项目崩溃了
-
@Vyacheslav 请尝试再运行一次。由于某种原因,第一次运行应用程序时它会崩溃。谢谢。
标签: ios swift orientation appdelegate