UINavigationController and autorotation

2019-01-22 02:50发布

I have a UIViewController that returns YES in shouldAutorotateToInterfaceOrientation: for UIDeviceOrientationPortrait and NO for everything else. With that view on the top of the stack, I use pushViewController:animated: to push a new UIViewController. The new controller returns YES for anything in shouldAutorotateToInterfaceOrientation:.

The first view refuses to rotate (as expected). Once the second view is pushed, the user can rotate the device and the UI will rotate (also as expected). If the second view is in landscape mode and the user presses the back button (which calls popViewControllerAnimated:), the first view will appear rotated (unexpected!).

If the user rotates the device back to portrait orientation, the view will rotate and then be stuck in portrait mode as before. This works but it's ugly for the user until they rotate back. So I'm in search of a way to make this view stay in portrait mode.

The only workaround I have found so far is to use -[UIDevice setOrientation:], which throws a warning (orientation is read-only) but works since it is actually defined. This is a huge hack and I'd like a real solution. In search of a real solution I attached GDB to the Photos application (MobileSlideshow.app) and discovered that it too uses -[UIDevice setOrientation:]. Being an internal application though I guess they have different rules.

Is there a correct way to achieve the expected autorotation behavior?

7条回答
闹够了就滚
2楼-- · 2019-01-22 03:31

A legal alternative to UIDevice setOrientation is as follows:

UIWindow* window = UIApplication.sharedApplication.keyWindow;
UIView* view = [window.subviews objectAtIndex:0];
[view removeFromSuperview];
[window addSubview:view];

This forces the current view controller to evaluate its orientation, calling shouldAutorotateToInterfaceOrientation and switching away from any prohibited orientations.

E.g. the following code would be used in a view controller that supports all orientations but whose parent only supports landscape:

- (void)popBack
{
    [self.navigationController popToRootViewControllerAnimated:YES]; 
}

- (IBAction)backPressed:(id)sender
{   
    portraitOrientationPermitted = NO;

    // Force the framework to re-evaluate the interface orientation.
    UIWindow* window = UIApplication.sharedApplication.keyWindow;
    UIView* view = [window.subviews objectAtIndex:0];
    [view removeFromSuperview];
    [window addSubview:view];

    [self performSelector:@selector(popBack) withObject:nil afterDelay:0.8];

    portraitOrientationPermitted = YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return portraitOrientationPermitted || 
        UIInterfaceOrientationIsLandscape(interfaceOrientation);
}
查看更多
登录 后发表回答