Zenman C
Zenman C

Reputation: 1733

How to maintain landscape or portrait mode when converting app to IPAD?

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.

Upvotes: 0

Views: 233

Answers (1)

Hitesh Borse
Hitesh Borse

Reputation: 479

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

Upvotes: 1

Related Questions