Stop UIView from roating into landscape

2019-07-22 17:32发布

问题:

I have a UIView thats inside a navigation controller, I am trying to prevent this view from going into Landscape however the method I am trying to use never fires.. code is below any help would be greatly appreciated..

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if(interfaceOrientation == UIInterfaceOrientationLandscapeRight)
    {
        return NO;
    }
    else if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
    {
        return NO;
    }
    return NO;
}

回答1:

You should set return NO; for the parent navigation controller or on a UIViewController, not a UIView.

Also, this works just the same with less code:

iOS 5.x

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

iOS 6

As of iOS 6, shouldAutorotateToInterfaceOrientation: is deprecated. If the view controller does not override the supportedInterfaceOrientations method, UIKit obtains the default rotations from the app delegate or the app’s Info.plist file.

You will need to use:

- (NSUInteger)supportedInterfaceOrientations NS_AVAILABLE_IOS(6_0);


回答2:

Another option is modifying Deployment Info.



回答3:

This method needs to be implemented in a UIViewController instance, not a UIView.

Also, you are in fact returning NO for all orientations, which is incorrect. You need to return YES for at least one orientation (most commonly UIInterfaceOrientationPortrait).