简体   繁体   English

viewWillTransitionToSize用于锁定方向

[英]viewWillTransitionToSize for locked orientation

Is there any way to detect the screen orientation even when the user has locked his orientation? 即使用户锁定了方向,是否有任何方法可以检测屏幕方向? My App uses a custom camera view and I would like to be able to save images in either landscape or portrait depending on the orientation. 我的应用程序使用自定义的相机视图,我希望能够根据方向以横向或纵向保存图像。 I am currently using the following code to detect the orientation, however this only works if the user has not locked it. 我目前正在使用以下代码来检测方向,但是,只有在用户未锁定它的情况下,这才起作用。

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        let orientation: UIDeviceOrientation = UIDevice.current.orientation

        switch (orientation) {
        case .portrait:
            print("Portrait")
        case .landscapeRight:
            print("Left")
        case .landscapeLeft:
            print("Right")
        default:break
        }
    }

If this is not the correct way to work with the camera orientation, please guide me in the right direction. 如果这不是使用相机方向的正确方法,请以正确的方向引导我。

I believe that the only way to do this is enabling both portrait and landscape mode in project: 我相信做到这一点的唯一方法是在项目中同时启用纵向和横向模式: 在此处输入图片说明

Then, override these properties in all your view controllers that don't need a landscape mode. 然后,在不需要横向模式的所有视图控制器中覆盖这些属性。

override var shouldAutorotate: Bool {
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return .portrait
}

In the view controller with embedded camera just set shouldAutorotate false and add extra supportedInterfaceOrientations that are used in landscape. 在带有嵌入式摄像头的视图控制器中,只需将shouldAutorotate设置为false并添加用于风景中的额外supportedInterfaceOrientations

Note that if you use UINavigationController or UITabBarController it will not work, so you should create these extensions: https://stackoverflow.com/a/39674618/5381663 请注意,如果您使用UINavigationController或UITabBarController,它将无法正常工作,因此您应该创建以下扩展名: https : //stackoverflow.com/a/39674618/5381663

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM