【问题标题】:Customize status bar background for UINavigationController为 UINavigationController 自定义状态栏背景
【发布时间】:2018-06-06 16:49:23
【问题描述】:

我想要一个带有白色文本的黑色状态栏。 我使用的一般方法是使用浅色状态栏来创建自定义黑色视图并将其添加到视图控制器的顶部

CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, statusBarHeight)];
view.backgroundColor = [UIColor blackColor];
[self.view addSubview:view];

如果视图控制器嵌入在导航控制器中,我会这样做

CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, -statusBarHeight, [UIScreen mainScreen].bounds.size.width, statusBarHeight)];
view.backgroundColor = [UIColor blackColor];
[self.navigationController.navigationBar addSubview:view];

然而这似乎不是一个非常优雅的解决方案,也许有更好的方法?

【问题讨论】:

    标签: ios objective-c iphone uinavigationcontroller


    【解决方案1】:

    您可以通过在 keywindow 上添加视图来做到这一点。无论您的应用是在 UINavigationController 下还是在 UIViewController 下运行,都无关紧要。我通过扩展 UIStatusBarStyle 来做到这一点,如下所示。

    extension UIStatusBarStyle {
        static func setbackground()  {
            let view  = UIView.init(frame: UIApplication.shared.statusBarFrame)
            view.backgroundColor = UIColor.black
            UIApplication.shared.keyWindow?.addSubview(view)
        }
    }
    

    现在从方法 didFinishLaunchingWithOptions 在 appdelegate 中调用此方法。

    UIStatusBarStyle.setbackground()
    

    另外,请确保您在 info.plist 文件中设置了

    View controller-based status bar appearance = NO
    Status bar style = Opaque black style
    

    【讨论】:

      猜你喜欢
      • 2011-03-14
      • 1970-01-01
      • 2015-08-01
      • 2011-03-15
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多