Last Updated: February 25, 2016
·
6.808K
· ktusznio

Setting UIBarButtonItem font

My Minutes uses rectangular "Done" buttons in place of the standard iOS "Back" buttons. I also use the Thonburi font throughout the app, and I had a hard time tracking down exactly how to set the font for these buttons. I ended up digging through Cheddar's source on github since Sam also uses a custom font.

Here's how to do it:

// Customize the navigation bar item buttons, including back buttons.
id barButtonAppearance = [UIBarButtonItem appearance];

NSDictionary *barButtonTextAttributes = @{
    UITextAttributeFont: [UIFont boldMyMinutesFontOfSize:16.0f],
    UITextAttributeTextShadowColor: [UIColor colorWithWhite:0.0f alpha:0.2f],
    UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)]
};

[barButtonAppearance setTitleTextAttributes:barButtonTextAttributes
                                   forState:UIControlStateNormal];
[barButtonAppearance setTitleTextAttributes:barButtonTextAttributes
                                   forState:UIControlStateHighlighted];

With the new font, I also needed to adjust the offsets of the buttons' text labels. Here's how to do that:

[barButtonAppearance setTitlePositionAdjustment:UIOffsetMake(0.0f, 0.0f)
                                  forBarMetrics:UIBarMetricsDefault];
[barButtonAppearance setBackButtonTitlePositionAdjustment:UIOffsetMake(-0.5f, -2.0f)
                                            forBarMetrics:UIBarMetricsDefault];