UINavigationController and autorotation

后端 未结 7 1626
灰色年华
灰色年华 2020-12-13 19:46

I have a UIViewController that returns YES in shouldAutorotateToInterfaceOrientation: for UIDeviceOrientationPortrait and NO

7条回答
  •  旧时难觅i
    2020-12-13 20:14

    It has been a old post but since it hasn't been solved. I would like to share my solution, for any others who might be in a headache.

    Objective: A UINavigationController and most of viewcontrollers in its stack fixed at portrait, except for one viewcontroller in the stack being allowed to rotate to both portrait and landscape.

    Problem: intuitively I set an selective shouldAutorotateToInterfaceOrientation by checking if the topViewController is the rotableViewController. However after poping back from the rotableViewController at the landscape mode, the navigationcontroller is now shown in the landscape mode although it is not allowed.

    Solution:The killer is to disallow the rotation at viewWillAppear and present & dismiss a modalViewController without animation.

    1. An appViewController is added to the window as the host viewController, i.e. rooter than the RootViewController;
    2. A navigationController is added to the appViewController, with delegate set to appViewController;
    3. In the AppViewController


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


    - (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
    {
        [viewController viewDidAppear:animated];
        canRotate = ([navigationController.topViewController isKindOfClass:[MyRotatable class]]);
    }
    


    - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
    {
        [viewController viewWillAppear:animated];
        if (![navigationController.topViewController isKindOfClass:[MyRotatable class]]) {
            canRotate = NO;
            UIViewController * blanck = [[UIViewController alloc] initWithNibName:nil bundle:nil];
            [self presentModalViewController:blanck animated:NO];
            [self dismissModalViewControllerAnimated:NO];
            [blanck release];
        }
    }
    

提交回复
热议问题