0
votes

I want to lock orientation in few UIViewcontroller

1) Loginview (support portrait Only ) UIViewcontroller having login button

2) On login button i call UITabbarController from storyboard, having 3tabs all tab are embedded UINavigationControllers.(Tab1,Tab2,Tab3)

3) On Tab1 (support both landscape and portrait )having button button1, from which i am push a UIViewcontroller Demo(support portrait Only ). like below

 Demo *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"Demo"];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];

The Demo is loaded successfully , but i want to lock its rotation to portrait so i create a Category of UINavigationController, but it still rotating.

#import <UIKit/UIKit.h>

@interface UINavigationController (Orientation)

@end

//==========

#import "UINavigationController+Orientation.h"
@implementation UINavigationController (Orientation)
-(BOOL)shouldAutorotate
{

    return YES;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortraitUpsideDown;;
}
@end

//------- Inside my Demo uiviewcontroller i but below code but it never called --------

-(BOOL)shouldAutorotate
{
    return NO;
}
-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

I read many post but non of them help ,Please Help me out how do i do it?

1

1 Answers

2
votes

Initial set orientation as Portrait only in Targets -> General -> Deployment Info (See Image Below)

enter image description here

In AppDelegate.h declare property:

@property (assign, nonatomic) BOOL shouldRotate;

In AppDelegate.m define

-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.shouldRotate)
        return UIInterfaceOrientationMaskAllButUpsideDown;
    else
        return UIInterfaceOrientationMaskPortrait;
}

In UIViewController Implemenatation set shouldRotate value like:

If you want to rotate then set YES

-(void) viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
        [(AppDelegate *)[[UIApplication sharedApplication] delegate] setShouldRotate:YES];
    }

else set NO

-(void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [(AppDelegate *)[[UIApplication sharedApplication] delegate] setShouldRotate:NO];
}

Note: setShouldRotate: always call in viewDidAppear:. So, whenever you switch the UIViewController it will work properly.

Hope this will work for you. All the best :)