Category on UINavigationBar - only for certain controllers
I successfully implemented a navigation bar with custom background following the answer posted at Custom background for UINavigationBar problems.
However, I would like to have the standard navigation bar for some of my开发者_运维问答 controllers and I have no clue how I can achieve this.
If I start a new project based on the Navigation-based Application template and just add the UINavigationBar category in separate .h and .m files, this category is applied immediately. No includes or whatever are necessary. How does this work?
Thanks for your help!
Here's a quick hack - use the tag property of your navigation bar to turn on the custom code i.e.
@implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
if (tag < 500) {
// Drawing code
UIImage *img = [UIImage imageNamed: @"navbar_background.png"];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, CGRectMake(0, 0, 320, self.frame.size.height), img.CGImage);
} else {
// Do the default drawing
}
}
@end
Now, navigation controllers with a tag less than 500 use your custom background. If you set the tag to be > 500, you get the default behaviour.
EDIT
As @MikeWeller correctly pointed out, we don't have access to the initial implementation of drawRect, our category has overridden it.
Take a look at this link for a solution - basically, it's a macro that you can include that gives you an extra method :
@implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
if (tag < 500) {
// Drawing code
UIImage *img = [UIImage imageNamed: @"navbar_background.png"];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, CGRectMake(0, 0, 320, self.frame.size.height), img.CGImage);
} else {
// Do the default drawing
invokeSupersequent(rect);
}
}
@end
NB I haven't tried this myself but have used other articles from this blog before with great success so I trust it :) Let us know how you get on!
@implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
if (tag < 500) {
// Drawing code
UIImage *img = [UIImage imageNamed: @"navbar_background.png"];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, CGRectMake(0, 0, 320, self.frame.size.height), img.CGImage);
} else {
// Do the default drawing
}
}
@end
Remeber this method will not work in iOS 5.0 because apple has changed the implementation of UINavigationBar so instead create a subclass of UINavigationBar and override the method there instead of creating category.
精彩评论