【问题标题】:Status bar background color does not change to custom color状态栏背景颜色不会更改为自定义颜色
【发布时间】:2018-06-23 23:58:58
【问题描述】:

当我将状态栏背景颜色更改为原生 UIColor.gray 时,它会发生变化。 但是当我想使用自定义颜色时,它会变成黑色。

UIApplication.shared.statusBarView?.backgroundColor = UIColor.gray - 此代码工作正常。状态栏背景颜色为灰色

UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 30/255, green: 30/255, blue: 30/255, alpha: 1) - 此代码工作不正确。状态栏背景颜色为黑色

【问题讨论】:

    标签: ios swift colors statusbar uistatusbar


    【解决方案1】:

    首先,在info.plist文件中设置基于View控制器的状态栏外观属性No。

    然后在AppDelegate类的didFinishLaunchingWithOptions方法中添加如下代码。

    extension UIApplication {
    var statusBarView: UIView? {
        if #available(iOS 13.0, *) {
            let tag = 5111
            if let statusBar = self.keyWindow?.viewWithTag(tag) {
                return statusBar
            } else {
                let statusBarView = UIView(frame: UIApplication.shared.statusBarFrame)
                statusBarView.tag = tag
    
                self.keyWindow?.addSubview(statusBarView)
                return statusBarView
            }
        } else {
            if responds(to: Selector(("statusBar"))) {
                return value(forKey: "statusBar") as? UIView
            }
        }
        return nil}
    }
    

    希望对你有帮助。

    【讨论】:

    • 我不知道为什么,但这是互联网上所有解决方案中唯一对我有用的解决方案......为什么像更改状态栏颜色这样简单的事情必须如此复杂?苹果,你是认真的吗?
    【解决方案2】:

    希望这对您在 Swift 4 中有所帮助。看起来像一个 hacky 技巧,但有效。

    您可以在应用程序启动期间或视图控制器的 viewDidLoad 期间设置状态栏的背景颜色。

    extension UIApplication {
    
        var statusBarView: UIView? {
            return value(forKey: "statusBar") as? UIView
        }
    
    }
    
    // Set upon application launch, if you've application based status bar
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
            return true
        }
    }
    
    
    or 
    // Set it from your view controller if you've view controller based statusbar
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
        }
    
    }
    



    结果如下:

    【讨论】:

    • @KeghamK.- 谢谢你的评论。一有机会我会检查并更新。
    【解决方案3】:

    代码没有错误,只是您提供的颜色是dark gray 本身。 (R:30,G:30,B:30) 代表dark gray,这就是status bar 中使用的颜色,将此颜色更改为其他颜色,例如(R:202,G:0,B:42),它将显示red 颜色。

    试试

    UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 202/255, green: 0/255, blue: 42/255, alpha: 1)

    【讨论】:

      猜你喜欢
      • 2015-09-26
      • 2019-11-20
      • 2016-10-16
      • 2015-10-09
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多