Prevent autorotate for one view controller?

蹲街弑〆低调 提交于 2019-11-30 03:55:09

When a UINavigationController is involved, create a category on the UINavigationController and override supportedInterfaceOrientations.

 #import "UINavigationController+Orientation.h"

 @implementation UINavigationController (Orientation)

-(NSUInteger)supportedInterfaceOrientations
{
   return [self.topViewController supportedInterfaceOrientations];
}

-(BOOL)shouldAutorotate
 {
    return YES;
 }

@end  

Now, iOS containers (such as UINavigationController) do not consult their children to determine whether they should autorotate.

How to create a category
1. Add a new file (Objective c- category under cocoa touch)
2. Category : Orientation on UINavigationController
3. Add the above code to UINavigationController+Orientation.m

Swift 3 version the accepted answer:

extension UINavigationController {

    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        // Change `.portrait` to whatever your default is throughout your app
        return topViewController?.supportedInterfaceOrientations ?? .portrait
    }

    open override var shouldAutorotate: Bool {
        return true
    }
}

As per the documentation.

A view controller can override the supportedInterfaceOrientations method to limit the list of supported orientations.

So we need to override shouldAutorotate and supportedInterfaceOrientation to target view controllers.

Typically, the system calls this method only on the root view controller of the window or a view controller presented to fill the entire screen.

This will work if you have very simple configuration like your target view controller is the rootViewController of window or being presented covering whole screen.

In case when configuration of target view controller is complex like embedded in some other container view controllers.

child view controllers use the portion of the window provided for them by their parent view controller and no longer participate directly in decisions about what rotations are supported.

So may be default implementation of these container view controllers not asking there children for there supportedInterfaceOrientation preference.

So to allow our target child view controller to specify there supportedIntefaceOrientation we need to tell there container view controller to do so.

You can also check my previous answer here.

and Understanding UIViewController rotation when embed in Container View Controllers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!