Skip to content

Instantly share code, notes, and snippets.

@Shilo
Last active July 16, 2016 12:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shilo/94ad6e957714c6151aa702e0cdf49794 to your computer and use it in GitHub Desktop.
Save Shilo/94ad6e957714c6151aa702e0cdf49794 to your computer and use it in GitHub Desktop.
iOS - Dynamically load navigation bar title image with interpolation. How to use: Set navigation title as "{image_name_here}"
#define NAV_PORTRAIT_HEIGHT 44
- (void)viewDidLoad {
[super viewDidLoad];
[self loadNavigationBarTitleImage];
}
- (void)loadNavigationBarTitleImage {
NSString *title = self.navigationItem.title;
NSInteger prefixLength = NAV_TITLE_IMAGE_PREFIX.length;
NSInteger suffixLength = NAV_TITLE_IMAGE_SUFFIX.length;
if (title.length > prefixLength + suffixLength && [title hasPrefix:NAV_TITLE_IMAGE_PREFIX] && [title hasSuffix:NAV_TITLE_IMAGE_SUFFIX]) {
NSString *imageName = [title substringWithRange:NSMakeRange(prefixLength, title.length-prefixLength-suffixLength)];
UIImage *image = [UIImage imageNamed:imageName];
if (image) {
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
CGRect imageFrame = imageView.frame;
imageFrame.size.height = self.navigationController.navigationBar.bounds.size.height * (imageFrame.size.height / NAV_PORTRAIT_HEIGHT);
imageView.frame = imageFrame;
self.navigationItem.titleView = imageView;
} else {
NSLog(@"Error loading navigation bar title image named: %@", imageName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment