Search code examples
iosswiftcocoa-touchuinavigationcontrolleruinavigationbar

How can I change the font of the back button for my navigation bar?


How can I change the font of the back button for my navigation bar.

The back button is either "back" or the title from the previous view controller.

I thought this viewDidLoad would work:

navigationController?.navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "FONTNAME", size: 20)!], forState: UIControlState.Normal)

but the leftBarButton? optional returns nil.


Solution

  • Just tested your code and it seems the reason that line is returning nil is actually because name: "FONTNAME" returns nil. So if you set that name attribute to a valid font name, the code should run without an error -- even if navigationController?.navigationItem.leftBarButtonItem is explicitly set to nil.

    But regardless, also as I've seen through testing, this line won't give you the result you apparently want. The leading navigationController optional shouldn't be there since it accesses your UINavigationController and not the current view. Simply use the UIViewController's own navigationItem property to access its leftBarButtonItem directly, ex:

    let backButton = UIBarButtonItem(title: "< Back", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
    navigationItem.leftBarButtonItem = backButton
    navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Chalkduster", size: 20)!], forState: UIControlState.Normal)
    

    Edit: From the comment you posted under this answer, it seems as if you don't actually want to set the leftBarButtonItem but the backBarButtonItem because you don't want to implement a custom action beyond going back to the previous view controller.

    So in that previous view controller (i.e. the view before you want to show your custom back button item), you can set your custom back button without an action like so:

    let backButton = UIBarButtonItem(title: "< Back", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
    backButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Chalkduster", size: 20)!], forState: UIControlState.Normal)
    navigationItem.backBarButtonItem = backButton