0

I'm currently adapting an iphone app to ipad and have implemented the following code in the viewController to maintain one of the views in landscape (the other views are in portrait):

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.dataSource = self
    collectionView.delegate = self

    //TODO: - Keep presentationView in landscape

    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
}

override func viewDidDisappear(_ animated: Bool) {
    let value = UIInterfaceOrientation.portrait.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .landscapeLeft
}

override var shouldAutorotate: Bool {
    return true
}

This works fine for the iphone but does not work when displaying the app on iPad i.e. the view rotates and can be seen in both portrait and landscape. Be grateful for any suggestions on how I can adapt the code to make it work on iPad.

Zenman C
  • 1,653
  • 13
  • 21
  • Code such as `UIDevice.current.setValue(value, forKey: "orientation")` is inappropriate. It's not supported (even if it might work under some conditions). Avoid hacks that require using private APIs. – rmaddy Jun 27 '19 at 06:11
  • 1
    Check this answer: https://stackoverflow.com/questions/28938660/how-to-lock-orientation-of-one-view-controller-to-portrait-mode-only-in-swift – Rahul Jun 27 '19 at 06:21
  • Thanks for the responses. The following in the link that Rahul posted was particularly useful: - Make sure that "Requires full screen" is checked in Target Settings -> General -> Deployment Info. supportedInterfaceOrientationsFor delegate will not get called if that is not checked. - – Zenman C Jun 27 '19 at 10:49

1 Answers1

1

Add method viewWillTransition(to:with:). Notifies the container that the size of its view is about to change.UIKit calls this method before changing the size of a presented view controller’s view. You can override this method in your own objects and use it to perform additional tasks related to the size change.

 override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
        // Update frame
    } else {
        print("Portrait")
         // Update frame
    }
}

enter image description here

Hitesh Borse
  • 479
  • 2
  • 12