Search code examples
iosswift3screen-orientationscreen-rotationxcode8

Swift manually rotate view controller


So I'm working on an iOS 10 app using Swift 3 and Xcode 8.3.3. In my app I have to take successively 8 pictures with indicators on the camera.

So I'm using AVCaptureVideoPreviewLayer for the custom camera and I need to set the view displaying the camera on landscape mode. I did it using this extension that I found on stackoverflow while searching for the problem.

struct AppUtility {

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {

        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    /// OPTIONAL Added method to adjust lock and rotate to the desired orientation
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {

        self.lockOrientation(orientation)

        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }

}

and in the viewDidLoad() of the customCameraView, I'm setting the locking the orientation to .landscapeLeft :

AppUtility.lockOrientation(.landscapeLeft)

before leaving the view I'm setting this in my viewWillDissapear method in order to unlock the orientation:

AppUtility.lockOrientation(.all)

The problem is that landscape mode in the customCameraView works only when the auto-rotation of the device is enabled (not locked) and when I get back to the previous view controller, it is initially displayed in landscapeLeft so I have to turn the device to put it portrait mode. this view is locked in portrait method using the AppUtility extension.

So I thought about always activate the auto-rotation by overriding the shouldAutoRotate var but it didn't work when the device auto-rotation is locked.

Then I thought about making sure that the auto-rotation is enabled before opening the camera but 100 of people on stackoverflow are saying that this is not possible.

So the perfect solution for me would be to always make the customCameraView in landscapeLeft mode and the previous view in portrait no matter if the rotate is activated or not.

I'm struggling on this bug for days now and a little help would be great.


Solution

  • iOS encourages developers to support both portrait and landscape, so it can be difficult to restrict one part of the app to be landscape while the other is portrait.

    One option that works pretty well is to restrict the entire app to portrait mode in the project settings, and apply a rotation transform to any view controllers that need to be landscape. This way, the view will look and behave like it is landscape, and you have full control over the rotation of your views.