iOS 13设置状态栏背景色

时间:2019-09-26 09:40:02

标签: swift statusbar ios13

我曾经有以下代码,但是升级到iOS 13之后,出现以下错误:

UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 94/225, green: 64/255, blue:204/255, alpha: 1.0)

在UIApplication上名为-statusBar或-statusBarWindow的应用程序:必须更改此代码,因为不再有状态栏或状态栏窗口。而是在窗口场景上使用statusBarManager对象。'

现在如何设置状态栏的背景色?

警告消息中提到了有关使用statusBarManager的信息,所以我做了类似的事情,但我无法使其正常工作。

var statusBar = UIView()

    if #available(iOS 13.0, *) {
        statusBar = UIView(frame: UIApplication.shared.keyWindow?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero)
        statusBar.backgroundColor = UIColor.red
        UIApplication.shared.keyWindow?.addSubview(statusBar)
    } else {
        //ios 12 and below
        UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 94/225, green: 64/255, blue:204/255, alpha: 1.0)
    }

2 个答案:

答案 0 :(得分:1)

库拉(Kuray)在这里为我提供了一个解决方案:

https://freakycoder.com/ios-notes-13-how-to-change-status-bar-color-1431c185e845

将以下内容添加到viewdidload。请转到他的中级职位,并给他一些鼓掌!

if #available(iOS 13.0, *) {
        let app = UIApplication.shared
        let statusBarHeight: CGFloat = app.statusBarFrame.size.height

        let statusbarView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: statusBarHeight))
        statusbarView.backgroundColor = UIColor.red
        view.addSubview(statusbarView)
    } else {
        let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
        statusBar?.backgroundColor = UIColor.red
    }

答案 1 :(得分:0)

代码适用于 Swift 5+ 和 iOS 13+

请参考答案:https://stackoverflow.com/a/64924164/7610245

在 UIViewController 扩展中添加了“statusBarColorChange()”。

func statusBarColorChange() {

if #available(iOS 13.0, *) {

    let statusBar = UIView(frame: UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero)
    statusBar.backgroundColor = .appThemeButtonsColor
        statusBar.tag = 100
    UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.addSubview(statusBar)

} else {

        let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
        statusBar?.backgroundColor = .appThemeButtonsColor

    }
}

希望会有所帮助:)