ios - 无法使用纵向模式获得横向图像选择器工作

标签 ios swift

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

enter image description here

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 中,添加此函数:

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

另外,在这个函数中:

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

此代码可能有优化,但这是您需要的核心功能。

让我知道这对您来说如何,是否有效,是否存在故障。

关于ios - 无法使用纵向模式获得横向图像选择器工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42911102/

相关文章:

cllocationmanager - Swift 中的 CLLocation Manager 获取用户位置

ios - RxSwift - 订阅行为(观察者 :)

ios - 加密 NSString

iphone - 企业应用数据安全

ios - IBAction 没有被解雇

ios - 媒体查询和视口(viewport)宽度 - 良好的 CSS 修复在 iPad 上不起作用

ios - 无法设置图像按钮- swift

ios - isExclusiveTouch 不适用于自定义 UIView

swift - 发送到网络服务的日期错误

ios - uitableview - 自定义图像在 cell.contentView 中持续加载