Swift:为iOS 13更改状态栏颜色

Mic*_*sen 4 statusbar ios swift

对于ios 13,我无法设置状态栏的文本颜色。如何获取statusBarManager的视图?如何仅更改文本颜色?

由于:

由于未捕获的异常“ NSInternalInconsistencyException”而终止应用程序,原因:“在UIApplication上名为-statusBar或-statusBarWindow的应用程序:此代码必须更改,因为不再有状态栏或状态栏窗口。而是在窗口场景上使用statusBarManager对象。”

我当前的代码:

    func setStatusBarTextColor(_ color: UIColor) {
        if #available(iOS 13.0, *) {
            // How to do for iOS 13??
        } else {
            if let statusBar = UIApplication.shared.value(forKey: "statusBar") as? UIView {
                statusBar.setValue(color, forKey: "foregroundColor")
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我已经找到了这个/sf/answers/4017632601/,但这不是我想要的

Pra*_*ngh 8

您可以像这样在 iOS 13 中使用:

   let statusBar =  UIView()
   statusBar.frame = UIApplication.shared.statusBarFrame
   statusBar.backgroundColor = UIColor.red
   UIApplication.shared.keyWindow?.addSubview(statusBar)
Run Code Online (Sandbox Code Playgroud)


Mau*_*tel 5

使用Swift 5.0的IOS 13.0和XCode 11.0 100%工作

    if #available(iOS 13.0, *) {


       let statusBar1 =  UIView()
       statusBar1.frame = UIApplication.shared.keyWindow?.windowScene?.statusBarManager!.statusBarFrame as! CGRect
       statusBar1.backgroundColor = UIColor.black

       UIApplication.shared.keyWindow?.addSubview(statusBar1)

    } else {

       let statusBar1: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
       statusBar1.backgroundColor = UIColor.black
    }
Run Code Online (Sandbox Code Playgroud)

  • iOS 13 中已弃用“keyWindow”。 (2认同)

Sat*_*tar -3

更新的答案

要更改状态栏上的文本颜色,您只需设置样式即可。(你不需要太多的选择,状态栏中的文本颜色可以是白色或黑色)

如果您想在视图控制器级别设置状态栏样式,请按照以下步骤操作:

  1. UIViewControllerBasedStatusBarAppearance如果您只需要在 UIViewController 级别设置状态栏样式,请在 .plist 文件中将 设为 YES 。
  2. preferredStatusBarStyle在你的视图控制器中覆盖。

如果您想更改 iOS 13 的状态栏背景,请使用以下代码:

extension UIApplication {

class var statusBarBackgroundColor: UIColor? {
    get {
        return statusBarUIView?.backgroundColor
    } set {
        statusBarUIView?.backgroundColor = newValue
    }
}

class var statusBarUIView: UIView? {
    if #available(iOS 13.0, *) {
        let tag = 987654321

        if let statusBar = UIApplication.shared.keyWindow?.viewWithTag(tag) {
            return statusBar
        }
        else {
            let statusBarView = UIView(frame: UIApplication.shared.statusBarFrame)
            statusBarView.tag = tag

            UIApplication.shared.keyWindow?.addSubview(statusBarView)
            return statusBarView
        }
    } else {
        if responds(to: Selector(("statusBar"))) {
            return value(forKey: "statusBar") as? UIView
        }
    }
    return nil
}}
Run Code Online (Sandbox Code Playgroud)