How to lock device orientation in iOS 7 and iOS 8

2019-05-16 09:09发布

问题:

I have a problem with my app. I cannot lock the orientation of my app. All I need to do is to lock one view controller to landscape mode and the rest are portrait.

This is hierarchy of my app.

*Navigation Controller
     *TabBarController
          *ViewControllers

回答1:

You only have to return NO from shouldAutorotate and the landscape orientation from supportedInterfaceOrientation in the one you want to be in landscape.

On the other, return NO too from shouldAutorotate method and portrait orientations mask from supportedInterfaceOrientation.

In all the viewControllers :

 -(BOOL)shouldAutorotate { 
     return NO; 
 } 

In the one you want in landscape :

- (NSUInteger)supportedInterfaceOrientations{ 
    return UIInterfaceOrientationMaskLandscape; 
} 
-    (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { 
    return UIInterfaceOrientationLandscapeLeft; 
} 

In the controllers you want in portrait :

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


回答2:

Use below 2 this methods to lock device orientation to landscape.

- (NSUInteger)supportedInterfaceOrientations{
[super supportedInterfaceOrientations];
return (UIInterfaceOrientationMaskLandscapeLeft |  UIInterfaceOrientationMaskLandscapeRight);
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if (interfaceOrientation==UIInterfaceOrientationLandscapeLeft || interfaceOrientation==UIInterfaceOrientationLandscapeRight)
{
    return YES;
}
// Return YES for supported orientations
return NO;
}


回答3:

With NavigationController

-(BOOL)shouldAutorotate 
-(NSUInteger)supportedInterfaceOrientations
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation

these method are never called , if you use 'show segue(push)'.

change segue 'showDetail' instead 'show'