导航栏背景颜色在 swift 5 中不起作用

NavigationBar background color not working in swift5

我在 swift5 中使用 NavigationBar。 NavigationBar 背景颜色显示黑色..这是我的图片

这是我的代码:

    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            
            self.navigationController?.navigationBar.tintColor = UIColor.red
            self.navigationController?.navigationBar.barTintColor = UIColor.green
            self.navigationController?.navigationBar.barTintColor = .red
            self.navigationItem.title = "ABC title"
            self.navigationController!.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
            self.navigationController?.navigationBar.isTranslucent = false
        }
    }

我的代码有什么问题?请帮助我

这就是 iOS 15 NavigationBars 使用 scrollEdgeAppearance 的原因,如果你想使用旧的外观,你必须像这样声明它:

override func viewDidLoad() {
        super.viewDidLoad()
        let appearance = UINavigationBarAppearance()
        appearance.configureWithOpaqueBackground()
        appearance.backgroundColor = .red
        appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
        self.navigationController?.navigationBar.standardAppearance = appearance;
        self.navigationController?.navigationBar.scrollEdgeAppearance = self.navigationController?.navigationBar.standardAppearance
        
        self.navigationItem.title = "ABC title"
    }

这就是结果:

您可以使用此代码简单地更改导航栏背景颜色

self.navigationController?.navigationBar.backgroundColor = UIColor.green