隐藏状态栏时,如何在UINavigationController中获取导航栏以更新其位置?

问题描述:

我的UINavigationController带有可见的导航栏. 我有一个特定的UIViewController,当将其推入导航堆栈时,我想隐藏状态栏.弹出该viewController后,我想再次显示状态栏.

I have a UINavigationController with a visible Navigation Bar. I have one particular UIViewController which I'd like to hide the status bar when pushed into the navigation stack. Once this viewController is popped I'd like to show the status bar again.

我将条形图隐藏在UIViewControllerviewWillAppear方法中,如下所示:

I'm hiding the bar in the viewWillAppear method of my UIViewController like this:

- (void) viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    [self.navigationController setWantsFullScreenLayout:YES];
    [[UIApplication sharedApplication] setStatusBarHidden:YES animated:YES];    
}

请注意,为清楚起见,我在此处设置setWantsFullScreenLayout:YES,但实际上我只是在Interface Builder中设置了此属性.

Note that I'm setting setWantsFullScreenLayout:YES here for clarity, but I'm actually just setting this property in Interface Builder.

问题: NavigationController的导航栏不会向上移动以占据现在隐藏的状态栏的空间.

The problem: The navigation bar of the NavigationController doesn't move up to take the space of the now hidden status bar.

hacky解决方案 我发现唯一可以刷新导航栏位置的方法是将其隐藏并再次显示,如下所示:

A hacky solution The only thing I found that worked to refresh the position of the nav bar was to hide it and show it again, like this:

[[UIApplication sharedApplication] setStatusBarHidden:YES animated:YES];
[self.navigationController setNavigationBarHidden:YES animated:NO];
[self.navigationController setNavigationBarHidden:NO animated:NO];

但这显然是黑客,必须有更好的方法.

but this is clearly a hack, there has got to be a better way.

我尝试过的其他事情:

  1. 在隐藏状态栏后,即在方法末尾,我尝试调用[super viewWillAppear].

我像这样在NavigationController.view上尝试了setNeedsLayout:

I tried setNeedsLayout on the navigationController.view like this:

[[UIApplication sharedApplication] setStatusBarHidden:YES animated:YES];    
[self.navigationController.view setNeedsLayout];

但这似乎不起作用.

任何帮助表示赞赏. 谢谢

Any help appreciated. Thanks

您可以通过两种方式来完成自己要问的事情.

There are two ways that you can do what you are asking.

一种方法是手动移动导航栏:

One is to manually move the navigation bar:

在viewWillAppear中:

In viewWillAppear:

    [UIApplication sharedApplication].statusBarHidden = YES;
    self.view.frame = [UIScreen mainScreen].applicationFrame;
    CGRect frame = self.navigationController.navigationBar.frame;
    frame.origin.y = 0;
    self.navigationController.navigationBar.frame = frame;

在viewWill中消失

In viewWillDisappear:

    [UIApplication sharedApplication].statusBarHidden = NO;
    CGRect frame = self.navigationController.navigationBar.frame;
    frame.origin.y = 20.0;
    self.navigationController.navigationBar.frame = frame;

如果您也想关闭导航栏,那么一切都会好起来的,尽管我怀疑那不是您想要的:

Things will also be okay if you are willing to turn off the navigation bar as well, although I suspect that is not what you wanted:

    [UIApplication sharedApplication].statusBarHidden = YES;
    self.navigationController.navigationBarHidden = YES;