簡體   English   中英

如何在 iOS 14、Swift 5 中將狀態欄的顏色更改為除明暗以外的自定義顏色?

[英]How to change the color of status bar to a custom color other than light and dark in iOS 14, Swift 5?

我想將狀態欄的顏色(電池百分比、時間和 wifi 等)更改為 Apple 提供的.lightContent.darkContent以外的自定義顏色(紅色、黃色、藍色等)。 甚至有可能這樣做嗎? 如果是,請幫我解決這個問題。 我已經在 google 和 stackoverflow 上看到了答案,但它們只更改了 backgroundColor,主要是棄用了 keyWindow。 我正在使用Swift 5 and iOS 14.4

if #available(iOS 13.0, *) {
    let app = UIApplication.shared
    let statusBarHeight: CGFloat = app.statusBarFrame.size.height
    
    let statusbarView = UIView()
    statusbarView.backgroundColor = UIColor.red
    view.addSubview(statusbarView)
  
    statusbarView.translatesAutoresizingMaskIntoConstraints = false
    statusbarView.heightAnchor
        .constraint(equalToConstant: statusBarHeight).isActive = true
    statusbarView.widthAnchor
        .constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
    statusbarView.topAnchor
        .constraint(equalTo: view.topAnchor).isActive = true
    statusbarView.centerXAnchor
        .constraint(equalTo: view.centerXAnchor).isActive = true
  
} else {
    let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
    statusBar?.backgroundColor = UIColor.red
}

就是這樣:) 不要忘記在 viewDidLoad function 上使用它。 如果您使用的是 TabBarController,則此代碼段應位於 viewWillAppear function 上。 這個很重要!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM