0

My app supports both landscape and portrait but I want to disable landscape rotation on one of my collectionViews and viewControllers. My code below works on viewController but not in collectionView. Any suggestions?

    override var shouldAutorotate: Bool{
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}
  • I dont think you can add that to a component like CollectionView, its a property of the ViewController. Guess the solution is to handle the constrains of the collection view when screen rotates. – Rakshith Nandish Dec 25 '17 at 09:44
  • So there is no way that I can disable rotation in my UICollectionViewController ? –  Dec 25 '17 at 09:49

1 Answers1

0

I always use this

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return .portrait
}

Also, there's no such thing as rotating UICollectionView, It's your ViewController

Just like in a car, the driver handles the entire car

Edit :

It might be the right code, but not in the right ViewController. For example, if the View Controller is embedded in a UINavigationController, the navigation controller can still rotate, causing the View Controller to still rotate. It really depends on your specific situation.

Assuming your ViewController is embedded into navigationController, Your best bet is subclassing UINavigationController

import UIKit    

class CustomNavigationController: UINavigationController {

    override func shouldAutorotate() -> Bool {
        if !viewControllers.isEmpty {
            // Check if this ViewController is the one you want to disable roration on
            if topViewController!.isKindOf(ViewController) {               //ViewController is the name of the topmost viewcontroller

                // If true return false to disable it
                return false
            }
        }
        // Else normal rotation enabled
        return true
       }
    }

If you want to disable autorotation throughout the navigation controller, remove the if condition and return false always

excitedmicrobe
  • 2,338
  • 1
  • 14
  • 30