Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I lock orientation for a specific view an Objective-C iPhone app in iOS 8?

I'm just trying to set up my app so that only one view can be viewed in landscape mode.

I've tried just about everything from shouldAutorotate to supportedInterfaceOrientation to preferedInterfaceOrientationForPresentation, and setting [UIDevice currentDevice]'s orientation to portrait. I have Landscape enabled in Info.plist and the project's general section.

like image 463
robestrong Avatar asked Aug 03 '15 18:08

robestrong


3 Answers

Firstly make your application portrait only in your info.plist

Create the following property in your AppDelegate class:

@property BOOL restrictRotation;

Then create the following method in your AppDelegate.m class:

-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if(self.restrictRotation)
        return UIInterfaceOrientationMaskPortrait;
    else
        return UIInterfaceOrientationMaskAll;
}

Create the following method in your ViewController and call it right before you want to permit landscape orientation. (Call it with true first in your viewDidLoad method to make sure rotation is restricted)

-(void) restrictRotation:(BOOL) restriction
{
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    appDelegate.restrictRotation = restriction;
}

like this:

[self restrictRotation:NO];

and after you are done with your landscape view and its dismissed, call this immediately:

[self restrictRotation:YES];

Hope this answers your question.

like image 63
Gurtej Singh Avatar answered Oct 14 '22 07:10

Gurtej Singh


also change orientation after locking it:

-(void)forceOrientation:(UIInterfaceOrientation)orientation{
    [[UIDevice currentDevice]setValue:[NSNumber numberWithInteger:orientation]forKey:@"orientation"];
}
  • set in app delegate
like image 39
Ofir Malachi Avatar answered Oct 14 '22 09:10

Ofir Malachi


For iOS 6 and above to clear the warning in AppDelegate while using Gurtej Singh answer you can replace the AppDelegate code with :

    - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window  API_AVAILABLE(ios(6.0)) API_UNAVAILABLE(tvos)
{
    if(self.restrictRotation)
        return UIInterfaceOrientationMaskPortrait;
    else
        return UIInterfaceOrientationMaskAll;
}
like image 44
Developer Avatar answered Oct 14 '22 07:10

Developer