Skip to content

Instantly share code, notes, and snippets.

@0xc010d
Created March 23, 2012 13:27
Show Gist options
  • Save 0xc010d/2170617 to your computer and use it in GitHub Desktop.
Save 0xc010d/2170617 to your computer and use it in GitHub Desktop.
@interface BaseNavigationController : UINavigationController
- (id)initWithRootViewController:(UIViewController *)rootViewController navigationBarBackgroundImage:(UIImage *)backgroundImage;
@end
#import "BaseNavigationController.h"
#import <objc/runtime.h>
#import <objc/message.h>
static const void *kNavigationBarBackgroundImageAssociatedObjectKey = "kNavigationBarBackgroundImageAssociatedObjectKey";
@interface BaseNavigationBar : UINavigationBar
@end
@implementation BaseNavigationController
- (void)dealloc {
[super dealloc];
}
- (id)initWithRootViewController:(UIViewController *)rootViewController {
return [self initWithRootViewController:rootViewController navigationBarBackgroundImage:nil];
}
- (id)initWithRootViewController:(UIViewController *)rootViewController navigationBarBackgroundImage:(UIImage *)backgroundImage {
self = [super initWithRootViewController:rootViewController];
if (backgroundImage) {
if ([self.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
[self.navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
} else {
object_setClass(self.navigationBar, [BaseNavigationBar class]);
objc_setAssociatedObject(self.navigationBar, kNavigationBarBackgroundImageAssociatedObjectKey, backgroundImage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
}
return self;
}
@end
@implementation BaseNavigationBar
- (void)dealloc {
objc_removeAssociatedObjects(self);
[super dealloc];
}
- (void)drawRect:(CGRect)rect {
UIImage *backgroundImage = objc_getAssociatedObject(self, kNavigationBarBackgroundImageAssociatedObjectKey);
if (backgroundImage) {
[backgroundImage drawInRect:self.bounds];
} else {
[super drawRect:rect];
}
}
@end
#import "BaseNavigationController.h"
@interface RootNavigationController : BaseNavigationController
@end
#import "RootNavigationController.h"
@implementation RootNavigationController
- (void)dealloc {
[super dealloc];
}
- (id)initWithRootViewController:(UIViewController *)rootViewController {
return [super initWithRootViewController:rootViewController navigationBarBackgroundImage:[UIImage imageNamed:@"RootNavigationBarBackground.png"]];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment