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

mde*_*ani 5 ios appdelegate swift swift4 ios11

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

小智 7

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

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

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

    self.navigationController?.navigationBar.barTintColor = UIColor.white
    
    Run Code Online (Sandbox Code Playgroud)
  2. 用于更改导航栏的标题和栏按钮颜色

    self.navigationController?.navigationBar.tintColor = UIColor.black
    
    Run Code Online (Sandbox Code Playgroud)
  3. 用于更改字体

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


aBi*_*l17 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
}
Run Code Online (Sandbox Code Playgroud)

并在 didFinishLaunchingWithOptions 中将此函数调用为 setupNavigationBarAppearance()。我正在使用相同的代码,并且运行良好。