无法通过纵向模式获取横向图像选择器

我的应用程序处于完全横向模式,但是当从相册中选择图像时,我被迫添加纵向模式。 我只想在选择图像时使用纵向模式。 现在它表现得很奇怪,当手机处于横向模式时没有方向锁定和选择图像时,图像选择器显示为一半。 右半部分是黑色,左边是景观中的图像选择器(所以是的,看起来很奇怪)。 这是我的设置:

在此处输入图像描述

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return .all } 

在viewDidLoad中的ViewController中(我需要在每个ViewController中添加它…):

 let value = UIInterfaceOrientation.landscapeLeft.rawValue UIDevice.current.setValue(value, forKey: "orientation") private func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.landscapeLeft } open override var shouldAutorotate: Bool { get { return false } } 

我已经查看了质疑这个问题的人的答案。 我只是无法让它工作:(

我不久前有类似的问题。 如果我理解你的问题是正确的,那么除非出现照片选择器,否则您希望应用程序保持横向模式。 这是你要做的:

  1. 进入您的设置并选中这三个方向选项:人像,左侧风景,右侧风景。
  2. 进入AppDelegate并添加此静态变量:

     static var canRotate = false { didSet{ UIDevice.current.setValue(canRotate ? UIInterfaceOrientation.portrait.rawValue : UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation") } } 
  3. 同样在您的AppDelegate中,添加此function:

     func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { if AppDelegate.canRotate { return .portrait } else { //return the orientation you want your app to be in return [.landscapeLeft, .landscapeRight] } } 

此时,您可以通过调用AppDelegate.canRotate = true或false来控制是否可以旋转设备

剩下的就是在你的图像选择器代码中添加这个变量,这是你做的:

 if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .camera imagePicker.allowsEditing = true AppDelegate.canRotate = true self.present(imagePicker, animated: true, completion: nil) } 

另外,在这个function中:

 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { AppDelegate.canRotate = false picker.dismiss(animated: true, completion: nil) } 

在这一个也是:

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { AppDelegate.canRotate = false picker.dismiss(animated: true, completion: nil) } 

可能会对此代码进行优化,但这是您需要的核心function。

让我知道这对你有用,如果它有效,有毛刺,或者不是。