Monday, 3 February 2014

Orientation Lock Code for Specified Pages in iOS App

Orientation Lock Code for Specified Pages in iOS Apps



For 5.0 & Below 5.0


-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return NO;
}



For 6.0 & Above 6.0

Code implemented in (void)didrotate & (void)viewwillappear

- (void)viewWillAppear:(BOOL)animated
{
    if (self.interfaceOrientation != UIInterfaceOrientationPortrait)
    {
        [[UIDevice currentDevice] performSelector:NSSelectorFromString(@"setOrientation:") withObject:(id)UIInterfaceOrientationPortrait];
    }
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    if (self.interfaceOrientation != UIInterfaceOrientationPortrait)
    {
        [[UIDevice currentDevice] performSelector:NSSelectorFromString(@"setOrientation:") withObject:(id)UIInterfaceOrientationPortrait];
    }
}


For 7.0, 8.0 Above 7.0, 8.0


Lock a Orientation for App in XCode 6.1  

In Project Settings should change into support orientation to Unlock(Tick-Mark) the all items.

The code used to one Time Orientation Lock. 
When run the (Portrait-Lock)code in your app, The app is support Autorotate Function. If you want to Autorotate, You can run the (Portrait-UnLock)code in your app. 

If want use in Single Page, Use the (Portrait-Lock)code in viewWillAppear (or) viewDidAppear and (Portrait-UnLock)code used in viewWillDisappear (or) Navigate Button (or) Back Button. 


AppDelegate.h File

@property (nonatomic) BOOL screenIsPortraitOnly;


AppDelegate.m File

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    NSUInteger orientations = UIInterfaceOrientationMaskPortrait;
    if (self.screenIsPortraitOnly)
    {
        return UIInterfaceOrientationMaskPortrait;
    }
    else
    {
        if(self.window.rootViewController)
        {
            UIViewController *presentedViewController = [[(UINavigationController *)self.window.rootViewController viewControllers] lastObject];
            orientations = [presentedViewController supportedInterfaceOrientations];
        }
        return orientations;
    }
}



ViewController.m File

//Orientation UnLock Code
-(void)viewWillAppear:(BOOL)animated
{
    [self portraitUnLock];
}

(or)

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:true];
    [self portraitUnLock];
}

//Orientation Lock Code
-(void)viewWillDisappear:(BOOL)animated
{
    [self portraitLock];
}

(or)

//Button Code
- (IBAction)Back_Clicked:(id)sender
{
    [self portraitLock];
[self.navigationController popViewControllerAnimated:YES];
}


-(void)portraitLock
{
    AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
    appDelegate.screenIsPortraitOnly = true;
}


-(void)portraitUnLock
{
    AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
    appDelegate.screenIsPortraitOnly = false;
}

No comments: