0

I know this has to be simple, but it's eluding me:

I have code in a UINavigationController that's doing a fine job of setting the font for the title of the navigation bar, along with the background color and the color of the navigation items:

override func viewDidLoad() {

    super.viewDidLoad()

    let navigationBarAppearace = UINavigationBar.appearance()

    navigationBarAppearace.tintColor = UIColor.white
    navigationBarAppearace.barTintColor = UIColor(colorLiteralRed: 46/255, green: 99/255, blue: 201/255, alpha: 1.0)
    navigationBarAppearace.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "OpenSans", size: 17)!]

}

but I can't get the font for the navigation items to change. I've tried a few things, including (in the same viewDidLoad):

self.navigationItem.backBarButtonItem?.setTitleTextAttributes([ NSFontAttributeName: UIFont(name: "OpenSans", size: 17)!], for: UIControlState.normal)

as well as (in viewDidLoad of one of the ViewControllers using the navbar:)

self.navigationController?.navigationItem.backBarButtonItem?.setTitleTextAttributes([ NSFontAttributeName: UIFont(name: "OpenSans", size: 17)!], for: UIControlState.normal)

I have the font in the plist, and am using it successfully in other parts of the project. I assume I'm just trying to do this the wrong way, can someone help?

Paul Degnan
  • 1,972
  • 1
  • 12
  • 28

2 Answers2

2

You can change the appearance of all UIBarButtonItems in you UINavigationViewController class:

UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: font!], for: UIControlState.normal)  

See more details here: Change font of back navigation bar button

bughana
  • 324
  • 5
  • 12
  • This worked, but I needed to put it in the App Delegate to catch the first navigator window, using iOS 11 swift 4.0 – user3069232 Jul 14 '18 at 07:48
0

if OpenSans is not in the plist file you would get fatal error: unexpectedly found nil while unwrapping an Optional value

so try

override func awakeFromNib() {
    let navigationBarAppearace = UINavigationBar.appearance()

    navigationBarAppearace.tintColor = UIColor.white
    navigationBarAppearace.barTintColor = UIColor(colorLiteralRed: 46/255, green: 99/255, blue: 201/255, alpha: 1.0)
    navigationBarAppearace.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "OpenSans", size: 17)!]
}

difference between awakeFromNib() and viewDidLoad() in swift

SpaceDust__
  • 4,844
  • 4
  • 43
  • 82