viewWillTransitionToSize用于锁定方向

时间:2017-07-19 08:04:46

标签: ios swift3 uideviceorientation

即使用户锁定了方向,有没有办法检测屏幕方向?我的应用程序使用自定义相机视图,我希望能够以横向或纵向保存图像,具体取决于方向。我目前正在使用以下代码来检测方向,但这仅在用户未锁定时才有效。

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
        }
    }

如果这不是使用相机方向的正确方法,请指导我正确的方向。

1 个答案:

答案 0 :(得分:0)

我认为唯一的方法是在项目中启用纵向和横向模式: enter image description here

然后,在所有不需要横向模式的视图控制器中覆盖这些属性。

override var shouldAutorotate: Bool {
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return .portrait
}

在具有嵌入式摄像头的视图控制器中,只需将 shouldAutorotate 设置为false,并添加在横向中使用的额外 supportedInterfaceOrientations

请注意,如果您使用UINavigationController或UITabBarController它将不起作用,因此您应该创建这些扩展:https://stackoverflow.com/a/39674618/5381663

相关问题