Search code examples
iosswiftswift2uinavigationbar

Swift change font and color of back button


I am developing an app in Swift 2.2. Now I want to change the back button font and color for a certain view. The view in question has a navigation controller as it's parent controller.

I've tried running both of the following lines in viewDidLoad of my ViewController

self.navigationController!.navigationItem.backBarButtonItem!.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Andes Rounded", size: 17)!], forState: .Normal)
self.navigationItem.backBarButtonItem!.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Andes Rounded", size: 17)!], forState: .Normal)

Neither throws any errors, but it doesn't make any difference to the back button. I've also tried running both of these

self.navigationController!.navigationItem.leftBarButtonItem!.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Andes Rounded", size: 17)!], forState: .Normal)   
self.navigationItem.leftBarButtonItem!.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Andes Rounded", size: 17)!], forState: .Normal)

This however throws an error (error unwrapping nil). How should I change the font and color of the nav bar back button correctly? Feels like I'm not modifying the right items...


Solution

  • If you want to set same color to bar buttons implicitly then in your AppDelegate, in didfinishlaunchingwithoptions, write:

     UINavigationBar.appearance().tintColor = UIColor.white //your desired color here
    

    Update :

    Put this in AppDelegate,

     UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Andes Rounded", size: 17)!], forState: .Normal) // your textattributes here
    

    Update 2 :

      UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UINavigationBar.classForCoder()]).setTitleTextAttributes(["attribute" : "value"], forState: .Normal)
    

    Hope this will help :)