Skip to content

Instantly share code, notes, and snippets.

@kukat
Last active March 31, 2021 15:42
Show Gist options
  • Save kukat/10228924 to your computer and use it in GitHub Desktop.
Save kukat/10228924 to your computer and use it in GitHub Desktop.
UINavigationBar Title with Image
// Icon
UIImage *headerIcon = [UIImage imageNamed:@"store32"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = headerIcon;
NSAttributedString *icon = [NSAttributedString attributedStringWithAttachment:textAttachment];
// space between icon and title
NSAttributedString *space = [[NSAttributedString alloc] initWithString:@" "];
// Title
NSAttributedString *title = [[NSAttributedString alloc] initWithString:self.navigationItem.title];
// new title
NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithAttributedString:icon];
[attributedTitle appendAttributedString:space];
[attributedTitle appendAttributedString:title];
// move text up to align with image
[attributedTitle addAttribute:NSBaselineOffsetAttributeName
value:@(10.0)
range:NSMakeRange(1, attributedTitle.length-1)];
UILabel *titleLabel = [UILabel new];
titleLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:17.f];
titleLabel.attributedText = attributedTitle;
[titleLabel sizeToFit];
self.navigationItem.titleView = titleLabel;
@spiderguy84
Copy link

I'm trying to implement this code, but all I am able to get it to do is show '...' at the bottom left corner of the UINavigationBar. What is happening?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment