Set Landscape or Portrait Orientation for a Single View Controller (Objective-C)

Hello All,

Today, I’ll talk to you all about setting only a single View Controller in a StoryBoard (with NavigationController) to either Portrait or Landscape Orientation.

So lets get started!

Firstly set the Device Orientation property of the project to allow Portrait.. Landscape Left and Landscape Right orientations.

Screen Shot 2016-07-24 at 5.14.15 PM.png

Next we point our attention to AppDelegate.m class of your project.

Copy the below snippet into your AppDelegate.m file. The below snippet will return the top ViewController in the UI Stack of the RootViewController

 

– (UIViewController *)topViewController{

return [self topViewController:[UIApplication sharedApplication].keyWindow.rootViewController];

}

– (UIViewController *)topViewController:(UIViewController *)rootViewController

{

if (rootViewController.presentedViewController == nil) {

return rootViewController;

}

if ([rootViewController.presentedViewController isMemberOfClass:[UINavigationController class]]) {

UINavigationController *navigationController = (UINavigationController *)rootViewController.presentedViewController;

UIViewController *lastViewController = [[navigationController viewControllers] lastObject];

return [self topViewController:lastViewController];

}

UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController;

return [self topViewController:presentedViewController];

}

Now add the below snippet in the AppDelegate file. This snippet will check the the current top View Controller in the RootViewController by its title.

And according to its title, will decide, what would be the Orientation of the View Controller.

In the below snippet, I have set the orientation to Landscape with a specific title and for the rest, I have set the orientation to Portrait.

A bit of a workaround, but it works for me.

– (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window

{

if ([[self topViewController].title isEqualToString: @”Enter your view controller title”])

{

return UIInterfaceOrientationMaskLandscape;

}

else return UIInterfaceOrientationMaskPortrait;

}

One More Thing!

Now lets point our focus towards the Storyboard. The above snippet / code will work only if you present your “Landscape” view controller Modally.

So,┬áin order to set the “Kind” property in the Segue to “Present Modally”. Screen Shot 2016-07-24 at 5.30.39 PM.png

Also, it would be better if you change the orientation of the View Controller to Landscape by changing the “Orientation” property to Landscape!

Screen Shot 2016-07-24 at 5.32.27 PM.png

I hope it helps!

Do comment your opinions!

Cheers!!

Rohant K!

Advertisements