Ios 如何更改状态栏的颜色?

Ios 如何更改状态栏的颜色?,ios,swift,Ios,Swift,在我的应用程序中,我使用图像作为我的ViewController的背景。对于项目设置中的状态栏,我设置:状态栏样式-默认值。我不在状态栏中使用任何其他内容 问题是当iOS暗模式启用时,我的状态栏变为白色。我需要它保持黑色。如何修复它 此外,我不想关闭应用程序中支持的iOS暗/光模式。因此Info.plist中的外观灯对我来说不太合适。对于每个ViewController,可以使用简单的覆盖方法设置状态栏颜色 override var preferredStatusBarStyle: UIStat

在我的应用程序中,我使用图像作为我的
ViewController
的背景。对于项目设置中的状态栏,我设置:
状态栏样式-默认值
。我不在状态栏中使用任何其他内容

问题是当iOS暗模式启用时,我的
状态栏变为白色。我需要它保持黑色。如何修复它


此外,我不想关闭应用程序中支持的iOS暗/光模式。因此
Info.plist
中的外观灯对我来说不太合适。

对于每个
ViewController
,可以使用简单的覆盖方法设置状态栏颜色

override var preferredStatusBarStyle: UIStatusBarStyle {
    if #available(iOS 13, *) {
        return .darkContent
    } else {
        return .default
    }
}

不要忘记在Info.plist中将基于视图控制器的状态栏外观设置为“是”。

将状态栏样式设置为“黑色内容”:

之后,添加info.plist查看基于控制器的状态栏外观,并将其设置为

更新

如果您只想在determinate controller中添加黑色内容,则会显示视图中的add SetNeedssStatusBarAppearanceUpdate,然后覆盖preferredStatusBarStyle:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    setNeedsStatusBarAppearanceUpdate()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
    if #available(iOS 13.0, *) {
        return .darkContent
    } else {
        return .default
    }
从导航控制器开始:

在场景代理中声明第一个导航控制器:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    window?.makeKeyAndVisible()
    let controller = UINavigationController(rootViewController: FirstViewController())
    controller.navigationBar.barStyle = .black
    window?.rootViewController = controller
}
在SecondViewController中,替代状态栏样式

override var preferredStatusBarStyle: UIStatusBarStyle {
    if #available(iOS 13.0, *) {
        return .darkContent
    } else {
        return .default
    }
}

在一些控制器中,我需要白色。因为如果我使用你的答案,我有这个-我更新我的答案。。。。如果我的答案满足您的问题,请用正确答案进行检查并投票…您不需要此If语句,但如果您想要添加return.default in else语句我需要它,因为应用程序支持iOS 12。但是,如果我使用iOS 13支持并使用您的代码,状态栏颜色不会改变。我正在使用断点并检查是否未调用“preferredStatusBarStyle”。我不知道为什么…您在else语句中添加了return.default吗?(下面//回顾早期版本)看看我的答案。。。