Search code examples
swiftuinavigationbarnavigationbar

How do I change navigationBar font in Swift?


This is what I have tried so far, but receiving an error (I have correctly implemented CaviarDreams to the project):

self.navigationController.navigationBar.titleTextAttributes = NSFontAttributeName[UIFont .fontWithName(CaviarDreams.ttf, size: 20)]

Error says: Use of unresolved identifier 'CaviarDreams


Solution

  • Try this:

    self.navigationController.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "CaviarDreams", size: 20)!]
    

    Edit: Now, UIFont must be unwrapped to be able to be used here.

    Swift 5 (+ safe handling of optional UIFont)

    self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedString.Key.font: UIFont(name: "Caviar-Dreams", size: 20) ?? UIFont.systemFont(ofSize: 20)]