How to set kerning (spacing between characters) on UINavigationBar title - Swift or Objective-C

Kyle Clegg picture Kyle Clegg · Dec 1, 2013 · Viewed 8.9k times · Source

I've got my nav bar mostly customized to my liking, but I'm trying to increase the kerning using NSKernAttributeName. I'm using the appearance proxy to set the nav bar to white text and a custom font, but when I try to add kerning it doesn't take effect.

[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                     [UIColor whiteColor], NSForegroundColorAttributeName,
                                                     [UIFont fontWithName:@"HelveticaNeue-Light" size:20.0], NSFontAttributeName,
                                                     [NSNumber numberWithFloat:2.0], NSKernAttributeName, nil]];

Do I need to do something else to add some of the less common attributes like kerning to the title label?

Answer

Jesús A. Álvarez picture Jesús A. Álvarez · Dec 1, 2013

According to the documentation, the titleTextAttributes of UINavigationBar only lets you specify the font, text color, text shadow color, and text shadow offset.

If you want to use other attributes, you can create a UILabel with the NSAttributedString you want, and set it as the titleView for your controller's navigationItem

For example:

UILabel *titleLabel = [UILabel new];
NSDictionary *attributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],
                             NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Light" size:20.0],
                             NSKernAttributeName: @2};
titleLabel.attributedText = [[NSAttributedString alloc] initWithString:self.navigationItem.title attributes:attributes];
[titleLabel sizeToFit];
self.navigationItem.titleView = titleLabel;