Cannot get landscape with portrait mode for image picker to work

前端 未结 1 575
醉梦人生
醉梦人生 2020-12-22 07:04

My app is in full landscape mode but when picking an image from the photo album I am forced to add portrait mode. I just want portrait mode to work when selecting an image.

相关标签:
1条回答
  • 2020-12-22 07:31

    I had a similar problem a while back. If I understand you question correctly, you want the app to stay in landscape mode unless the photo picker is presented. Here is what you have to do:

    1. Go into your settings and make these three orientation options are checked: Portrait, Landscape Left, Landscape Right.
    2. Go into your AppDelegate and add this static variable:

      static var canRotate = false {
          didSet{
            UIDevice.current.setValue(canRotate ? UIInterfaceOrientation.portrait.rawValue : UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
          }
      }
      
    3. Also in your AppDelegate, add this 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]
          }
      }
      

    At this point, you can control the whether or not you can rotate the device by calling AppDelegate.canRotate = true or false

    All that is left is to add this variable in your image picker code, here's what you do:

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

    Also, in this function:

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

    And in this one as well:

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

    There may be optimizations for this code but this is the core functionality you'll need.

    Let me know how this goes for you, if it works, glitches, or what not.

    0 讨论(0)
提交回复
热议问题