无法通过代码在运行时更改导航栏颜色?

Unable to change navigation bar color during runtime via code?

我针对 iOS 14.5

进行了测试

我们希望提供在运行时更改导航栏颜色的功能。

但是,我注意到以下代码不再有任何效果。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        navigationController?.navigationBar.backgroundColor = UIColor.red
        navigationController?.navigationBar.tintColor = UIColor.red
        UINavigationBar.appearance().barTintColor = UIColor.red
    }
}

但是,如果我直接在 Storyboard 中完成,它会工作得很好。


我们希望能够在运行时更改各种不同的颜色(通过单击用户按钮)

有谁知道为什么上面的代码坏了?

谢谢。

p/s 我可以确认 navigationController 不是零。

您可以尝试将它添加到您的 AppDelegate 中吗?我认为它会起作用,如果您不希望所有应用程序都使用它,那么您的代码可以正常工作,我已经使用过它并且它像图片中那样工作以下:

在 iOS 13 及更高版本上,您必须使用新的 UINavigationBarAppearance api 才能获得正确的颜色。

public extension UINavigationBar {

    func applyPlainAppearanceFix(barTintColor: UIColor, tintColor: UIColor) {
        
        if #available(iOS 13, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = barTintColor
            
            self.standardAppearance = appearance
            self.compactAppearance = appearance
            self.scrollEdgeAppearance = appearance
        }
        
        self.isTranslucent = false
        self.barTintColor = barTintColor
        self.backgroundColor = barTintColor
        self.tintColor = tintColor
    }

}

从调用站点来看应该是这样的

navigationController?.navigationBar.applyPlainAppearanceFix(barTintColor: .red, tintColor: .white)