通过编程更改UINavigationbar的背景色和标题字体/颜色

6

我希望能够在iOS 11和Swift 4中通过AppDelegate编程地更改导航栏的背景颜色、标题字体和颜色。我知道如何在Xcode中完成这个任务,但是没有找到最新的编程方法。

5个回答

7
以下是仅针对特定ViewControllers执行此操作的步骤。
我创建了一个名为BaseViewController的文件,它是所有ViewController的父类。以下代码已添加到BaseViewController的viewDidLoad()方法中。
  1. For changing the Navigation bar's background color

    self.navigationController?.navigationBar.barTintColor = UIColor.white
    
  2. For changing Navigation bar's title and Bar button colors

    self.navigationController?.navigationBar.tintColor = UIColor.black
    
  3. For changing font

    self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font : UIFont.sourceSansPro(ofSize: 18.0), NSAttributedStringKey.kern:1.5]
    

5
您可以使用以下代码更改背景颜色和标题字体。
func setupNavigationBarAppearance() {
    UINavigationBar.appearance().tintColor = .black
    UINavigationBar.appearance().shadowImage = UIImage.imageFromColor(.black, width: 1.0, height: 1.0)?.resizableImage(withCapInsets: .zero, resizingMode: .tile)
    UINavigationBar.appearance().isTranslucent = false

    let font:UIFont = UIFont(name: "ProximaNova-Bold", size: 18.0)!
    let navbarTitleAtt = [
        NSAttributedStringKey.font:font,
        NSAttributedStringKey.foregroundColor: UIColor.white
    ]
    UINavigationBar.appearance().titleTextAttributes = navbarTitleAtt
}

在didFinishLaunchingWithOptions中调用此函数,函数名为setupNavigationBarAppearance()。我正在使用相同的代码,并且它能很好地工作。


1
谢谢。我使用了以下代码来设置导航栏的颜色:UINavigationBar.appearance().barTintColor = Colors.accent。 - mdehghani
这个答案将设置您应用程序中所有导航栏的外观。如果您只需要更改一个控制器,请尝试下面的答案,作者是:Kamal Kumar Lakshman - SPS

2

对于AppDelegate

将以下代码放入AppDelegatedidFinishLaunchingWithOptions中:

    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.white
    UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white]
    UINavigationBar.appearance().isTranslucent = false

NSAttributedStringKey已更名,因此现在这一行应该是:UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white] - Klemens Zleptnig

2

只需使用UINavigationBar.appearance()

例如:

UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.white]

或者

UINavigationBar.appearance().barTintColor = .blue


0

iOS 15现在已经可以

navigationController.navigationBar.backgroundColor = .white

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接