我的应用程序背景是黑色的,但在iOS 7中,状态栏变成了透明的。所以我什么也看不见,只有角落里的绿色电池指示灯。如何将状态栏文本颜色改为白色,就像在主屏幕上一样?


当前回答

如果我使用UINavigationController,我在iOS 9和Swift 2.0中做这个

self.navigationController?.navigationBar.barStyle = UIBarStyle.Black

如果我使用模态segue

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return .LightContent
}

其他回答

在ios7上,如果你想使用UIViewControllerBasedStatusBarAppearance == YES,并且你的根视图控制器是UINavigationController,你应该这样做 子类化它并重载childViewControllerForStatusBarStyle,例如:

- (UIViewController*) childViewControllerForStatusBarStyle
{
    return self.viewControllers.lastObject;
}

在这之后,preferredStatusBarStyle将在被推送的视图控制器上被调用。

extension UIApplication {

    var statusBarView: UIView? {
        return value(forKey: "statusBar") as? UIView
    }
}

在.plist文件中设置UIViewControllerBasedStatusBarAppearance为YES。 在viewDidLoad做一个[self setNeedsStatusBarAppearanceUpdate]; 增加如下方法: ——(UIStatusBarStyle) preferredStatusBarStyle { 返回UIStatusBarStyleLightContent; }

注意:这并不适用于UINavigationController内部的控制器,请参阅Tyson的评论如下:)

Swift 3 -这将工作在UINavigationController中的控制器。将此代码添加到控制器中。

// Preferred status bar style lightContent to use on dark background.
// Swift 3
override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

Swift 5和SwiftUI

对于SwiftUI,我创建了一个名为HostingController.swift的新swift文件

import Foundation
import UIKit
import SwiftUI

class HostingController: UIHostingController<ContentView> {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

然后更改SceneDelegate.swift中的以下代码行

window.rootViewController = UIHostingController(rootView: ContentView())

to

window.rootViewController = HostingController(rootView: ContentView())

如果你想将它设置为任何颜色,请使用下面的代码。

id statusBarWindow = [[UIApplication sharedApplication] valueForKey:@"statusBarWindow"];
id statusBar = [statusBarWindow valueForKey:@"statusBar"];

SEL setForegroundColor_sel = NSSelectorFromString(@"setForegroundColor:");
if([statusBar respondsToSelector:setForegroundColor_sel]) {
    // iOS 7+
    [statusBar performSelector:setForegroundColor_sel withObject:YourColorHere];
                                                                 ^^^^^^^^^^^^^
}

我知道我正在访问私有API,但我已经在许多项目中使用了这个,苹果已经批准了它。

在提交应用程序时,将此代码发送到Apple的评论部分,并告知您正在使用此代码更改状态栏的颜色。

是的,不要忘记下面的内容。

如果你的UIViewController在UINavigationController中,你必须设置BarStyle:

-[UINavigationBar setBarStyle:UIBarStyleBlack]

原始答案在这里

https://devforums.apple.com/message/844264#844264