以编程方式更改UINavigationbar背景颜色和标题字体/颜色

时间:2018-05-04 07:15:58

标签: ios swift swift4 ios11 appdelegate

我想在iOS 11中以编程方式更改导航栏背景颜色,标题字体和颜色,从AppDelegate更改swift 4。我知道如何使用Xcode进行操作,但没有找到以编程方式执行此操作的最新解决方案。

4 个答案:

答案 0 :(得分:2)

以下是仅针对特定ViewControllers执行此操作的步骤。

我创建了一个BaseViewController文件,它是我所有ViewControllers的父文件。并将以下代码添加到BaseViewController的viewDidLoad()中。

  1. 用于更改导航栏的背景颜色

    self.navigationController?.navigationBar.barTintColor = UIColor.white
    
  2. 用于更改导航栏的标题和栏按钮颜色

    self.navigationController?.navigationBar.tintColor = UIColor.black
    
  3. 用于更改字体

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

答案 1 :(得分:1)

AppDelegate

将以下代码放在didFinishLaunchingWithOptions中的AppDelegate中:

    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

答案 2 :(得分:1)

您可以使用以下代码更改背景颜色和标题字体。

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中的此func称为setupNavigationBarAppearance()。我使用相同的代码,它工作正常。

答案 3 :(得分:0)

只需使用UINavigationBar.appearance()

即可

例如:

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

UINavigationBar.appearance().barTintColor = .blue

相关问题