我正在使用一个选择器视图,允许用户为整个应用程序选择颜色主题。

我计划改变导航栏的颜色,背景和可能的标签栏(如果可能的话)。

我一直在研究如何做到这一点,但找不到任何Swift的例子。谁能给我一个代码的例子,我需要用来改变导航栏的颜色和导航栏的文本颜色?

选取器视图已经设置好,我正在寻找更改UI颜色的代码。


当前回答

iOs 14 +

init() {        
    let appearance = UINavigationBarAppearance()
    appearance.shadowColor = .clear // gets also rid of the bottom border of the navigation bar
    appearance.configureWithTransparentBackground() 
    UINavigationBar.appearance().standardAppearance = appearance
    UINavigationBar.appearance().scrollEdgeAppearance = appearance
}

其他回答

Swift 4, iOS 12和Xcode 10更新

只需在viewDidLoad()中放入一行

navigationController?.navigationBar.barTintColor = UIColor.red

如果你有定制的导航控制器,你可以使用上面的代码片段。 在我的例子中,我使用了如下的代码段。

Swift 3.0, XCode 8.1版本

navigationController.navigationBar.barTintColor = UIColor.green

导航栏文本:

navigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.orange]

这是非常有益的谈话。

以下代码适用于iOS 15

if #available(iOS 15, *) {
        // Navigation Bar background color
        let appearance = UINavigationBarAppearance()
        appearance.configureWithOpaqueBackground()
        appearance.backgroundColor = UIColor.yourColor
        
        // setup title font color
        let titleAttribute = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 25, weight: .bold), NSAttributedString.Key.foregroundColor: UIColor.yourColor]
        appearance.titleTextAttributes = titleAttribute
        
        navigationController?.navigationBar.standardAppearance = appearance
        navigationController?.navigationBar.scrollEdgeAppearance = appearance
    }

Swift 3和Swift 4兼容Xcode 9

一个更好的解决方案是为常见的导航栏创建一个类

我有5个控制器,每个控制器的标题都改为橙色。因为每个控制器都有5个导航控制器,所以我不得不从检查器或代码中改变每一个颜色。

所以我做了一个类,而不是改变每个导航栏从代码我只是分配这个类,它在所有5个控制器代码重用能力。 你只需要将这个类分配给每个控制器就可以了。

import UIKit

   class NabigationBar: UINavigationBar {
      required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
    commonFeatures()
 }

   func commonFeatures() {

    self.backgroundColor = UIColor.white;
      UINavigationBar.appearance().titleTextAttributes =     [NSAttributedStringKey.foregroundColor:ColorConstants.orangeTextColor]

 }


  }

在iOS 15中,UIKit扩展了scrollEdgeAppearance的使用,默认情况下它会生成透明的背景,用于所有导航栏。 设置scrollEdgeAppearance如下代码。

if #available(iOS 15, *) {
        let appearance = UINavigationBarAppearance()
        appearance.configureWithOpaqueBackground()
        appearance.backgroundColor = < your tint color >
        navigationController?.navigationBar.standardAppearance = appearance;
        navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
    }