Search code examples
iosuinavigationbarorientationuiinterfaceorientationlandscape-portrait

Get UINavigationBar landscape height while device is in portrait


I have a simple question: I want to find out the height of a UINavigationBar in landscape while my device is in portrait. Is this possible and if so, how?

Some background:

UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectZero];
[navBar sizeToFit];

NSLog(@"navBar: %@", NSStringFromCGRect(navBar.frame));

This returns the correct height for the current device orientation, for example 44. That means that UINavigationBar's sizeToFit method must somehow look at the current device orientation. Is there any way to get find out what the height would be in landscape without going to landscape?


Solution

  • OK, this is one possible solution that works:

    @interface TestVC : UIViewController
    @property (assign, nonatomic) UIInterfaceOrientationMask orientationMask;
    @end
    
    @implementation TestVC
    - (BOOL)shouldAutorotate
    {
        return NO;
    }
    
    - (NSUInteger)supportedInterfaceOrientations
    {
        return _orientationMask;
    }
    @end
    
    
    @implementation ViewController
    
    - (IBAction)getNavigationBarHeight:(id)sender {
        TestVC *vc = [[TestVC alloc] init];
    
        if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
            vc.orientationMask = UIInterfaceOrientationMaskLandscapeLeft;
        } else {
            vc.orientationMask = UIInterfaceOrientationMaskPortrait;
        }
    
        [self presentViewController:vc animated:NO completion:^{
            UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectZero];
    
            [navBar sizeToFit];
    
            NSLog(@"navBar frame in 'opposite' orientation: %@", NSStringFromCGRect(navBar.frame));
    
        }];
        [self dismissViewControllerAnimated:NO completion:nil];
    }
    
    @end