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

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

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

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


当前回答

导航栏:

navigationController?.navigationBar.barTintColor = UIColor.green

用你想要的任何UIColor替换greenColor,如果你喜欢,你也可以使用RGB。

导航栏文本:

navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.orange]

用你喜欢的颜色替换orangeColor。

标签栏:

tabBarController?.tabBar.barTintColor = UIColor.brown

标签栏文本:

tabBarController?.tabBar.tintColor = UIColor.yellow

最后两个,用你选择的颜色替换brownColor和yellowColor。

其他回答

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

Swift 3.0, XCode 8.1版本

navigationController.navigationBar.barTintColor = UIColor.green

导航栏文本:

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

这是非常有益的谈话。

斯威夫特3

你可以在ViewDidLoad()中使用简单的一行代码

//Change Color
    self.navigationController?.navigationBar.barTintColor = UIColor.red
//Change Text Color
    self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]

我的观点是:

a)设置导航栏。barTintColor / titleTextAttributes工作在任何视图(推,添加..等在init..

B)设置外观并非处处适用:

你可以在AppDelegate上调用它 ”“一级视图 如果你在随后的推送视图中再次调用它,MNOT是否工作

SwiftUI 注释:

a)不适用(没有navigationBar,除非你通过UIViewControllerRepresentable trick..) b)对SwiftUI有效:相同的行为。

UINavigationBar.appearance().barTintColor = UIColor(red: 46.0/255.0, green: 14.0/255.0, blue: 74.0/255.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]

只需将这一行粘贴到代码中的didFinishLaunchingWithOptions中。

如果你使用iOS 13或14和大标题,并想改变导航栏的颜色,使用以下代码:

参考barTintColor不适用时导航栏是大标题

    fileprivate func setNavigtionBarItems() {
        if #available(iOS 13.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithDefaultBackground()
            appearance.backgroundColor = .brown
//            let naviFont = UIFont(name: "Chalkduster", size: 30) ?? .systemFont(ofSize: 30)
//            appearance.titleTextAttributes = [NSAttributedString.Key.font: naviFont]
            
            navigationController?.navigationBar.prefersLargeTitles = true
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = appearance
            //navigationController?.navigationBar.compactAppearance = appearance
        } else {
            // Fallback on earlier versions
            navigationController?.navigationBar.barTintColor = .brown
        }
    }

这花了我1个小时来找出我的代码中的错误:(,因为我使用大标题,很难用largeTitle改变tintColor,为什么苹果让它这么复杂,这么多行只是做一个tintColor的navigationBar。