iOS 7中在导航栏隐藏时如何更改状态栏的颜色?

5

我知道如何通过以下方式更改导航栏(和状态栏)的颜色:

self.navigationController.navigationBar.barTintColor = [UIColor redColor];

但是当我隐藏导航栏时,状态栏颜色会恢复到透明的颜色。

如何在隐藏导航栏时仍保持状态栏颜色与barTintColor相同?


在其后添加一个子视图,该子视图具有相同的色调。 - Maximilian Litteral
可能有所帮助的是状态栏始终是透明的。将一个 UIView 放在其后面与将一个 UINavigationBar 放在其后面没有任何区别。 - nhgrif
@nhgrif 是的,没错,但状态栏是320 x 20,与导航栏的尺寸不同。 - Enrico Susatyo
7个回答

6
这对我很有用(在Swift中):
let statusBarBGView = UIView(frame: UIApplication.sharedApplication().statusBarFrame)
statusBarBGView.backgroundColor = .whiteColor() //color of your choice
view.addSubview(statusBarBGView)

我的问题是我把navigationBar设置为隐藏,这导致statusBar的背景变得透明。这样一来,当tableView被滚动时,它的单元格会显示在statusBar的后面。


6
你只需要在当前视图中添加一个带有正确状态栏测量值的UIView,然后更改颜色即可。
以下是一些示例代码。首先获取状态栏的框架:
 //The statusBarFrame returns the frame in screen coordinates. I believe the correct way to get what this corresponds to in view coordinates is to do the following:
- (CGRect)statusBarFrameViewRect:(UIView*)view 
{
    CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
    CGRect statusBarWindowRect = [view.window convertRect:statusBarFrame fromWindow: nil];
    CGRect statusBarViewRect = [view convertRect:statusBarWindowRect fromView: nil];
    return statusBarViewRect;
}
//source: https://dev59.com/5m865IYBdhLWcg3wTclY

然后使用以下代码在viewDidload方法中创建你的视图或者在隐藏导航栏时创建:

UIView *statusBarUnderLay = [[UIView alloc] initWithFrame:[self statusBarFrameViewRect:self.view]];
[statusBarUnderLay setBackgroundColor:[UIColor yellowColor]];
[self.view addSubview:statusBarUnderLay];

然后,就完成了。


你们想看一份Swift版本的吗?或者这份代码已经足够简单易懂,可以轻松转换? - Pavan

2

在状态栏下添加一个 UIView,并将其 backgroundColor 属性设置为导航栏的 barTintColor


2

我的解决方案很简单,就是设置视图控制器视图的背景颜色。例如:

[self.view setBackgroundColor:[UIColor blackColor]];

当操作系统选择不显示状态栏时,需要处理添加视图的情况。


1
我发现使用InterfaceBuilder有一个简单的方法来解决这个问题。 我的问题是这样的,在隐藏导航栏后出现了一个烦人的白色间隙。

[Before[1]

然后我取消选中这两个选项。

options

然后它就可以工作了。

after## Heading ##


0

这解决了我的问题:

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

0
self.navigationController?.navigationBarHidden = true 之后设置 self.tableView.contentInset = UIEdgeInsetsZero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接